����JFIF��`�`�����Viewing File: /home/u820193700/domains/throtllr.com/public_html/js/pages/dealer/DealerDashboard.js
const { Routes, Route, Link, useLocation, useNavigate } = ReactRouterDOM;
const { useState, useEffect } = React;
const resolveMediaPath = (url) => {
    if (!url) return '';
    if (url.startsWith('http') || url.startsWith('blob:')) return url;
    const base = (window.API_BASE_URL || '').replace('/backend/api', '');
    return `${base.replace(/\/$/, '')}/${url.replace(/^\//, '')}`;
};

function DealerDashboard({ user, setUser }) {
    const location = useLocation();
    const navigate = useNavigate();
    const [previewTour, setPreviewTour] = useState(null);

    return (
        <div className="dashboard-container">
            <aside className="dashboard-sidebar">
                <div style={{ padding: '0 20px', marginBottom: '20px' }}>
                    <h3 style={{ fontSize: '1rem', color: 'var(--text-muted)' }}>DEALER PORTAL</h3>
                    <p style={{ fontSize: '0.9rem', color: 'var(--text-main)', fontWeight: 'bold' }}>{user?.showroom_name || user?.name || 'Showroom'}</p>
                </div>
                <ul className="sidebar-nav">
                    <li><Link to="/dealer" className={`sidebar-link ${location.pathname === '/dealer' ? 'active' : ''}`}><i className="fa-solid fa-gauge"></i> Dashboard</Link></li>
                    <li><Link to="/dealer/tours" className={`sidebar-link ${location.pathname.includes('/tours') ? 'active' : ''}`}><i className="fa-solid fa-motorcycle"></i> My Tours</Link></li>
                    <li><Link to="/dealer/bookings" className={`sidebar-link ${location.pathname.includes('/bookings') ? 'active' : ''}`}><i className="fa-solid fa-ticket"></i> Bookings</Link></li>
                    <li><Link to="/dealer/blogs" className={`sidebar-link ${location.pathname.includes('/blogs') ? 'active' : ''}`}><i className="fa-solid fa-pen-nib"></i> My Travel Blogs</Link></li>
                    <li><Link to="/dealer/packages" className={`sidebar-link ${location.pathname.includes('/packages') ? 'active' : ''}`}><i className="fa-solid fa-box-open"></i> Admin Packages</Link></li>
                    <li><Link to="/dealer/profile" className={`sidebar-link ${location.pathname.includes('/profile') ? 'active' : ''}`}><i className="fa-solid fa-store"></i> Profile & Wallet</Link></li>
                </ul>
            </aside>
            <div className="dashboard-content">
                <Routes>
                    <Route path="/" element={<DealerOverview />} />
                    <Route path="/tours" element={<DealerTours user={user} previewTour={previewTour} setPreviewTour={setPreviewTour} />} />
                    <Route path="/bookings" element={<DealerBookings />} />
                    <Route path="/blogs" element={<DealerBlogs />} />
                    <Route path="/packages" element={<DealerPackages setPreviewTour={setPreviewTour} />} />
                    <Route path="/profile" element={<DealerProfile user={user} setUser={setUser} />} />
                </Routes>
            </div>
        </div>
    );
}

function DealerOverview() {
    const [stats, setStats] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        window.fetchAPI('/dealer/dashboard.php')
            .then(res => {
                setStats(res.data || {});
                setLoading(false);
            })
            .catch(err => {
                console.error(err);
                setLoading(false);
            });
    }, []);

    if (loading) return <div>Loading...</div>;

    return (
        <div>
            <h2 className="mb-4">Dealer Overview</h2>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '20px' }}>
                <div className="card" style={{ padding: '20px' }}>
                    <h3 style={{ color: 'var(--text-muted)', fontSize: '0.9rem', margin: 0 }}>Total Tours Hosted</h3>
                    <p style={{ fontSize: '2rem', fontWeight: 'bold', margin: '5px 0' }}>{stats?.tours_hosted || 0}</p>
                </div>
                <div className="card" style={{ padding: '20px' }}>
                    <h3 style={{ color: 'var(--text-muted)', fontSize: '0.9rem', margin: 0 }}>Total Bookings</h3>
                    <p style={{ fontSize: '2rem', fontWeight: 'bold', margin: '5px 0' }}>{stats?.total_bookings || 0}</p>
                </div>
                <div className="card" style={{ padding: '20px', borderLeft: '4px solid var(--success)' }}>
                    <h3 style={{ color: 'var(--text-muted)', fontSize: '0.9rem', margin: 0 }}>Total Earned</h3>
                    <p style={{ fontSize: '2rem', fontWeight: 'bold', margin: '5px 0', color: 'var(--success)' }}>₹{stats?.total_earned || 0}</p>
                </div>
                <div className="card" style={{ padding: '20px', borderLeft: '4px solid var(--warning)' }}>
                    <h3 style={{ color: 'var(--text-muted)', fontSize: '0.9rem', margin: 0 }}>Pending Settlement</h3>
                    <p style={{ fontSize: '2rem', fontWeight: 'bold', margin: '5px 0', color: 'var(--warning)' }}>₹{stats?.pending_balance || 0}</p>
                </div>
            </div>

            <div className="card mt-4 p-4">
                <h3>Quick Actions</h3>
                <div className="d-flex gap-3 mt-3">
                    <Link to="/dealer/tours" className="btn"><i className="fa-solid fa-plus"></i> Create New Tour</Link>
                    <Link to="/dealer/packages" className="btn btn-outline"><i className="fa-solid fa-box-open"></i> Browse Admin Packages</Link>
                </div>
            </div>
        </div>
    );
}

function DealerTours({ user, previewTour, setPreviewTour }) {
    const [tours, setTours] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showForm, setShowForm] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [showMediaFor, setShowMediaFor] = useState(null);

    // Form state
    const [formData, setFormData] = useState({
        id: '', title: '', description: '', start_location: '', end_location: '',
        route_details: '', start_date: '', duration_days: '', price: '',
        max_riders: '', difficulty: 3, bike_eligibility: '', image_url: '', whatsapp_group_link: '',
        route_description: '', tarmac_pc: 70, offroad_pc: 30, max_altitude: '14,500 ft', 
        route_image_file: null, main_image_file: null,
        main_image_source: 'file', route_image_source: 'file',
        route_image_url: '' // Added missing field
    });

    const fetchTours = () => {
        setLoading(true);
        window.fetchAPI('/dealer/tours.php')
            .then(res => {
                setTours(res.data || []);
                setLoading(false);
            })
            .catch(err => {
                console.error(err);
                setLoading(false);
            });
    };

    useEffect(() => {
        fetchTours();
    }, []);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            const formDataObj = new FormData();
            Object.keys(formData).forEach(key => {
                if (key !== 'route_image_file' && key !== 'main_image_file') {
                    formDataObj.append(key, formData[key]);
                }
            });
            if (formData.route_image_file) {
                formDataObj.append('route_image_file', formData.route_image_file);
            }
            if (formData.main_image_file) {
                formDataObj.append('main_image_file', formData.main_image_file);
            }
            if (formData.id) {
                formDataObj.append('tour_id', formData.id);
            }

            const res = await window.fetchAPI('/dealer/tours.php', {
                method: 'POST',
                body: formDataObj
            });

            // Instead of immediate success, fetch the draft for preview
            if (res.tour_id) {
                const tourRes = await window.fetchAPI(`/tours.php?id=${res.tour_id}`).catch(() => ({ data: { ...formData, id: res.tour_id, status: 'draft' } }));
                
                // Use the data from server to ensure we have the correct image paths if uploaded
                const serverData = tourRes.data || {};
                setPreviewTour({ 
                    ...formData, 
                    ...serverData,
                    id: res.tour_id, 
                    status: 'draft' 
                });
                setShowForm(false);
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        } catch (err) {
            alert(err.message || 'Failed to create tour');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleEditDraft = (t) => {
        setFormData({
            id: t.id,
            title: t.title,
            description: t.description,
            start_location: t.start_location,
            end_location: t.end_location,
            route_details: t.route_details,
            start_date: t.start_date,
            duration_days: t.duration_days,
            price: t.price,
            max_riders: t.max_riders,
            difficulty: t.difficulty,
            bike_eligibility: t.bike_eligibility,
            image_url: t.image_url,
            whatsapp_group_link: t.whatsapp_group_link || '',
            route_description: t.route_description || '',
            tarmac_pc: t.tarmac_pc || 70,
            offroad_pc: t.offroad_pc || 30,
            max_altitude: t.max_altitude || '14,500 ft',
            route_image_file: null,
            main_image_file: null,
            route_image_url: t.route_image_url || '',
            main_image_source: t.image_url && t.image_url.startsWith('http') ? 'url' : 'file',
            route_image_source: t.route_image_url && t.route_image_url.startsWith('http') ? 'url' : 'file'
        });
        setPreviewTour(t);
        setShowForm(false);
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    const handleApprove = async () => {
        if (!previewTour) return;
        setIsSubmitting(true);
        try {
            await window.fetchAPI('/dealer/tours.php', {
                method: 'PUT',
                body: JSON.stringify({ tour_id: previewTour.id, status: 'pending' })
            });
            alert('Tour submitted for admin approval!');
            setPreviewTour(null);
            setFormData({
                title: '', description: '', start_location: '', end_location: '', route_details: '', start_date: '',
                duration_days: '', price: '', max_riders: '', difficulty: 3, bike_eligibility: '', image_url: '',
                whatsapp_group_link: '',
                route_description: '', tarmac_pc: 70, offroad_pc: 30, max_altitude: '14,500 ft', route_image_file: null, main_image_file: null
            });
            fetchTours();
        } catch (err) {
            alert(err.message || 'Failed to submit tour');
        } finally {
            setIsSubmitting(false);
        }
    };

    if (loading) return <div>Loading tours...</div>;

    return (
        <div>
            <div className="d-flex justify-between align-center mb-4">
                <h2>My Tours</h2>
                <button className="btn" onClick={() => { 
                    if (!showForm) setPreviewTour(null); // Clear preview when opening form
                    setShowForm(!showForm); 
                }}>
                    {showForm ? 'Cancel' : <React.Fragment><i className="fa-solid fa-plus"></i> Host New Tour</React.Fragment>}
                </button>
            </div>

            {showForm && (
                <div className="card mb-4">
                    <div className="card-body">
                        <h3>Create New Tour</h3>
                        <p className="text-muted mb-4">New tours undergo review by THROTLLR before going live.</p>
                        <form onSubmit={handleSubmit}>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
                                <div className="form-group">
                                    <label className="form-label">Tour Title</label>
                                    <input type="text" className="form-control" required value={formData.title} onChange={e => setFormData({ ...formData, title: e.target.value })} placeholder="e.g. Spiti Valley Adventure" />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Start Date</label>
                                    <input type="date" className="form-control" required value={formData.start_date} onChange={e => setFormData({ ...formData, start_date: e.target.value })} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Start Location</label>
                                    <input type="text" className="form-control" required value={formData.start_location} onChange={e => setFormData({ ...formData, start_location: e.target.value })} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">End Location</label>
                                    <input type="text" className="form-control" required value={formData.end_location} onChange={e => setFormData({ ...formData, end_location: e.target.value })} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Duration (Days)</label>
                                    <input type="number" className="form-control" required min="1" value={formData.duration_days} onChange={e => setFormData({ ...formData, duration_days: e.target.value })} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Price per Rider (₹)</label>
                                    <input type="number" className="form-control" required min="0" value={formData.price} onChange={e => setFormData({ ...formData, price: e.target.value })} />
                                </div>
                                <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                    <label className="form-label">Route Itinerary (Stops/Days)</label>
                                    <textarea className="form-control" rows="3" required value={formData.route_details} onChange={e => setFormData({ ...formData, route_details: e.target.value })} placeholder="Day 1: Arrival at Manali&#10;Day 2: Manali to Jispa&#10;..."></textarea>
                                </div>
                                <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                    <label className="form-label">Description</label>
                                    <textarea className="form-control" rows="4" required value={formData.description} onChange={e => setFormData({ ...formData, description: e.target.value })}></textarea>
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Max Riders</label>
                                    <input type="number" className="form-control" required min="1" value={formData.max_riders} onChange={e => setFormData({ ...formData, max_riders: e.target.value })} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Difficulty Level (1-5)</label>
                                    <input type="number" className="form-control" required min="1" max="5" step="0.5" value={formData.difficulty} onChange={e => setFormData({ ...formData, difficulty: e.target.value })} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Bike Eligibility</label>
                                    <input type="text" className="form-control" required value={formData.bike_eligibility} onChange={e => setFormData({ ...formData, bike_eligibility: e.target.value })} placeholder="e.g. Min 350cc Royal Enfield only" />
                                </div>
                                <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                    <label className="form-label">Main Tour Image *</label>
                                    <div className="d-flex gap-3 mb-2">
                                        <label style={{ fontSize: '0.85rem', cursor: 'pointer' }}>
                                            <input type="radio" name="main_image_source" value="file" checked={formData.main_image_source === 'file'} onChange={() => setFormData({ ...formData, main_image_source: 'file' })} /> Local Upload
                                        </label>
                                        <label style={{ fontSize: '0.85rem', cursor: 'pointer' }}>
                                            <input type="radio" name="main_image_source" value="url" checked={formData.main_image_source === 'url'} onChange={() => setFormData({ ...formData, main_image_source: 'url' })} /> Image URL
                                        </label>
                                    </div>
                                    {formData.main_image_source === 'file' ? (
                                        <input type="file" className="form-control" accept="image/*" required={!formData.image_url} onChange={e => setFormData({ ...formData, main_image_file: e.target.files[0] })} />
                                    ) : (
                                        <input type="url" className="form-control" required value={formData.image_url} onChange={e => setFormData({ ...formData, image_url: e.target.value })} placeholder="https://example.com/tour-main.jpg" />
                                    )}
                                    {formData.image_url && formData.main_image_source === 'file' && <div className="text-muted small">Current: {formData.image_url}</div>}
                                </div>
                                <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                    <label className="form-label">WhatsApp Group Link (Optional but Recommended)</label>
                                    <input type="url" className="form-control" value={formData.whatsapp_group_link} onChange={e => setFormData({ ...formData, whatsapp_group_link: e.target.value })} placeholder="https://chat.whatsapp.com/..." />
                                </div>

                                <div style={{ gridColumn: '1 / -1', borderTop: '1px solid var(--border-color)', paddingTop: '20px', marginTop: '10px' }}>
                                    <h4 style={{ color: 'var(--primary-color)', marginBottom: '15px' }}>Premium Route Details</h4>
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Route Map Image Source</label>
                                    <div className="d-flex gap-3 mb-2">
                                        <label style={{ fontSize: '0.85rem', cursor: 'pointer' }}>
                                            <input type="radio" name="route_image_source" value="file" checked={formData.route_image_source === 'file'} onChange={() => setFormData({ ...formData, route_image_source: 'file' })} /> Upload
                                        </label>
                                        <label style={{ fontSize: '0.85rem', cursor: 'pointer' }}>
                                            <input type="radio" name="route_image_source" value="url" checked={formData.route_image_source === 'url'} onChange={() => setFormData({ ...formData, route_image_source: 'url' })} /> URL
                                        </label>
                                    </div>
                                    {formData.route_image_source === 'file' ? (
                                        <input type="file" className="form-control" accept="image/*" onChange={e => setFormData({ ...formData, route_image_file: e.target.files[0] })} />
                                    ) : (
                                        <input type="url" className="form-control" value={formData.route_image_url || ''} onChange={e => setFormData({ ...formData, route_image_url: e.target.value })} placeholder="https://example.com/route-map.jpg" />
                                    )}
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Max Altitude</label>
                                    <input type="text" className="form-control" value={formData.max_altitude} onChange={e => setFormData({ ...formData, max_altitude: e.target.value })} placeholder="e.g. 14,500 ft" />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Tarmac (%)</label>
                                    <input type="number" className="form-control" min="0" max="100" value={formData.tarmac_pc} onChange={e => {
                                        const val = Math.min(100, Math.max(0, parseInt(e.target.value) || 0));
                                        setFormData({ ...formData, tarmac_pc: val, offroad_pc: 100 - val });
                                    }} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Off-road (%)</label>
                                    <input type="number" className="form-control" min="0" max="100" value={formData.offroad_pc} onChange={e => {
                                        const val = Math.min(100, Math.max(0, parseInt(e.target.value) || 0));
                                        setFormData({ ...formData, offroad_pc: val, tarmac_pc: 100 - val });
                                    }} />
                                </div>
                                <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                    <label className="form-label">Premium Route Description</label>
                                    <textarea className="form-control" rows="3" value={formData.route_description} onChange={e => setFormData({ ...formData, route_description: e.target.value })} placeholder="Describe the personality of the tracks, scenic highlights, and technical challenges..."></textarea>
                                </div>
                            </div>
                            <button type="submit" className="btn mt-3 w-100" disabled={isSubmitting}>
                                {isSubmitting ? 'Saving...' : 'Preview Tour Listing'}
                            </button>
                        </form>
                    </div>
                </div>
            )}

            {previewTour && (
                <div className="card mb-4" style={{ border: '2px solid var(--primary-color)' }}>
                    <div className="card-body">
                        <div className="d-flex justify-between align-center mb-3">
                            <h3 style={{ margin: 0 }}>Step 2: Preview Your Listing</h3>
                            <div className="d-flex gap-2">
                                <button className="btn btn-outline" onClick={() => { setPreviewTour(null); setShowForm(true); }}>Edit Again</button>
                                <button className="btn btn-secondary" onClick={() => setPreviewTour(null)}>Close Preview</button>
                                <button className="btn" onClick={handleApprove} disabled={isSubmitting}>
                                    {isSubmitting ? 'Submitting...' : 'Approve & Submit for Approval'}
                                </button>
                            </div>
                        </div>
                        <p className="text-muted mb-4">This is how your tour will appear to potential riders. Please review all details carefully.</p>

                        {/* Improved Tour Details Preview */}
                        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(300px, 400px) 1fr', gap: '40px' }}>
                            {/* Card Preview (Home Page Style) */}
                            <div>
                                <h4 style={{ marginBottom: '15px', color: 'var(--text-muted)', fontSize: '0.8rem', textTransform: 'uppercase' }}>Home Page Card Preview</h4>
                                <div className="card" style={{ width: '100%', maxWidth: '350px' }}>
                                    <img 
                                        src={formData.main_image_file ? URL.createObjectURL(formData.main_image_file) : resolveMediaPath(previewTour.image_url || 'https://images.unsplash.com/photo-1612080352932-520e737c0505?w=500')} 
                                        alt="Tour" 
                                        className="card-img" 
                                    />
                                    <div className="card-body">
                                        <h3 className="card-title">{previewTour.title || 'Tour Title'}</h3>
                                        <p style={{ fontSize: '0.85rem', color: 'var(--primary-color)', marginBottom: '5px' }}>
                                            <i className="fa-solid fa-building" style={{ marginRight: '5px' }}></i> Hosted by: {user?.showroom_name || 'Your Showroom'}
                                        </p>
                                        <div className="d-flex justify-between align-center mt-2 mb-2">
                                            <span style={{ fontSize: '0.9rem', color: 'var(--text-muted)' }}>
                                                <i className="fa-regular fa-calendar" style={{ marginRight: '5px' }}></i>
                                                {previewTour.start_date ? new Date(previewTour.start_date).toLocaleDateString() : 'Date'} ({previewTour.duration_days} Days)
                                            </span>
                                        </div>
                                        <div className="d-flex justify-between align-center mb-3">
                                            <span style={{ fontSize: '0.9rem', color: 'var(--text-muted)' }}>
                                                Available Slots: <span style={{ color: 'var(--success)', fontWeight: 'bold' }}>{previewTour.max_riders}/{previewTour.max_riders}</span>
                                            </span>
                                            <span style={{ fontSize: '1rem', color: '#fbbf24' }}>
                                                {Array.from({ length: 5 }).map((_, i) => {
                                                    const diff = parseFloat(previewTour.difficulty || 3);
                                                    if (i < Math.floor(diff)) return <i key={i} className="fa-solid fa-star"></i>;
                                                    if (i === Math.floor(diff) && diff % 1 !== 0) return <i key={i} className="fa-solid fa-star-half-stroke"></i>;
                                                    return <i key={i} className="fa-regular fa-star"></i>;
                                                })}
                                            </span>
                                        </div>
                                        <div className="d-flex justify-between align-center mt-3 pt-3" style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }}>
                                            <span style={{ fontSize: '1.2rem', fontWeight: 'bold', color: 'var(--primary-color)' }}>₹{previewTour.price}</span>
                                            <button className="btn btn-outline" style={{ padding: '5px 15px' }} disabled>View</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Hero Preview (Tour Details Style) */}
                            <div>
                                <h4 style={{ marginBottom: '15px', color: 'var(--text-muted)', fontSize: '0.8rem', textTransform: 'uppercase' }}>Tour Details Hero Preview</h4>
                                <div style={{ backgroundColor: '#18181b', borderRadius: '12px', overflow: 'hidden', border: '1px solid #3f3f46' }}>
                                    <div style={{ height: '300px', backgroundColor: '#27272a', position: 'relative' }}>
                                        <img 
                                            src={formData.main_image_file ? URL.createObjectURL(formData.main_image_file) : resolveMediaPath(previewTour.image_url || 'https://images.unsplash.com/photo-1558981403-c5f9899a28bc?w=1200')} 
                                            alt="Hero" 
                                            style={{ width: '100%', height: '100%', objectFit: 'cover', opacity: 0.7 }} 
                                        />
                                        <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '30px', background: 'linear-gradient(transparent, rgba(0,0,0,0.9))' }}>
                                            <h1 style={{ fontSize: '1.8rem', marginBottom: '10px', textTransform: 'uppercase', fontWeight: 900 }}>{previewTour.title}</h1>
                                            <div className="d-flex gap-4" style={{ fontSize: '0.9rem' }}>
                                                <span><i className="fa-solid fa-location-dot" style={{ color: 'var(--primary-color)' }}></i> {previewTour.start_location}</span>
                                                <span><i className="fa-solid fa-calendar"></i> {previewTour.start_date ? new Date(previewTour.start_date).toLocaleDateString() : ''}</span>
                                                <span><i className="fa-solid fa-clock"></i> {previewTour.duration_days} Days</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div style={{ padding: '25px' }}>
                                        <div className="card" style={{ backgroundColor: '#1e1e1e', padding: '15px 25px' }}>
                                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))', gap: '15px' }}>
                                                <div>
                                                    <div style={{ fontSize: '0.6rem', color: '#888', textTransform: 'uppercase' }}>Duration</div>
                                                    <div style={{ fontWeight: 'bold' }}>{previewTour.duration_days} Days</div>
                                                </div>
                                                <div>
                                                    <div style={{ fontSize: '0.6rem', color: '#888', textTransform: 'uppercase' }}>Difficulty</div>
                                                    <div style={{ fontWeight: 'bold' }}>{previewTour.difficulty} / 5</div>
                                                </div>
                                                <div style={{ textAlign: 'right' }}>
                                                    <div style={{ fontSize: '0.6rem', color: '#888', textTransform: 'uppercase' }}>Price</div>
                                                    <div style={{ fontWeight: '900', color: 'var(--primary-color)', fontSize: '1.2rem' }}>₹{previewTour.price}</div>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="mt-4">
                                            <h5 style={{ color: 'var(--primary-color)', marginBottom: '10px' }}>Route Map Preview</h5>
                                            <div style={{ background: '#27272a', borderRadius: '8px', padding: '15px', border: '1px solid #3f3f46' }}>
                                                <div style={{ textAlign: 'center', marginBottom: '15px' }}>
                                                    {formData.route_image_file ? (
                                                        <img 
                                                            src={URL.createObjectURL(formData.route_image_file)} 
                                                            alt="Route Map" 
                                                            style={{ maxWidth: '100%', maxHeight: '300px', objectFit: 'contain' }} 
                                                        />
                                                    ) : (
                                                        <div style={{ padding: '40px', color: 'var(--text-muted)' }}>
                                                            {previewTour.route_image_url ? (
                                                                <img src={resolveMediaPath(previewTour.route_image_url)} alt="Route Map" style={{ maxWidth: '100%', maxHeight: '300px', objectFit: 'contain' }} />
                                                            ) : (
                                                                <React.Fragment><i className="fa-solid fa-map fa-3x mb-2"></i><br/>No route map uploaded</React.Fragment>
                                                            )}
                                                        </div>
                                                    )}
                                                </div>
                                                {previewTour.route_description && (
                                                    <p style={{ fontSize: '0.85rem', color: '#d4d4d8', marginBottom: '20px', lineHeight: '1.6', whiteSpace: 'pre-wrap' }}>
                                                        {previewTour.route_description}
                                                    </p>
                                                )}
                                                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px', textAlign: 'center' }}>
                                                    <div>
                                                        <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>ALTITUDE</div>
                                                        <div style={{ fontWeight: 'bold' }}>{previewTour.max_altitude}</div>
                                                    </div>
                                                    <div>
                                                        <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>TARMAC</div>
                                                        <div style={{ fontWeight: 'bold' }}>{previewTour.tarmac_pc}%</div>
                                                    </div>
                                                    <div>
                                                        <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>OFF-ROAD</div>
                                                        <div style={{ fontWeight: 'bold' }}>{previewTour.offroad_pc}%</div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            <div className="table-responsive">
                <table style={{ width: '100%', borderCollapse: 'collapse', backgroundColor: 'var(--bg-card)', borderRadius: '8px', overflow: 'hidden' }}>
                    <thead>
                        <tr style={{ backgroundColor: 'var(--bg-lighter)', borderBottom: '1px solid var(--border-color)', textAlign: 'left' }}>
                            <th style={{ padding: '15px' }}>Tour Title</th>
                            <th style={{ padding: '15px' }}>Date</th>
                            <th style={{ padding: '15px' }}>Difficulty</th>
                            <th style={{ padding: '15px' }}>Status</th>
                            <th style={{ padding: '15px' }}>Price</th>
                            <th style={{ padding: '15px' }}>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {tours.map(t => (
                            <DealerTourRowWithAddons key={t.id} t={t} setPreviewTour={setPreviewTour} fetchTours={fetchTours} handleEditDraft={handleEditDraft} />
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

function DealerTourMediaManager({ tourId, tourTitle }) {
    const [media, setMedia] = useState([]);
    const [loading, setLoading] = useState(false);
    const [form, setForm] = useState({ title: '', media_type: 'image', media_url: '' });
    const [file, setFile] = useState(null);
    const [saving, setSaving] = useState(false);

    const fetchMedia = () => {
        setLoading(true);
        window.fetchAPI(`/tour_media.php?tour_id=${tourId}`)
            .then(res => { setMedia(res.data || []); setLoading(false); })
            .catch(() => setLoading(false));
    };

    useEffect(() => { fetchMedia(); }, [tourId]);

    const handleAdd = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            const formData = new FormData();
            formData.append('tour_id', tourId);
            formData.append('title', form.title);
            formData.append('media_type', form.media_type);

            if (form.media_type === 'youtube') {
                formData.append('media_url', form.media_url);
            } else if (file) {
                formData.append('media_file', file);
            } else {
                alert('Please provide a file or YouTube link');
                setSaving(false);
                return;
            }

            await window.fetchAPI('/tour_media.php', { method: 'POST', body: formData });
            setForm({ title: '', media_type: 'image', media_url: '' });
            setFile(null);
            fetchMedia();
        } catch (err) { alert(err.message); }
        setSaving(false);
    };

    const handleDelete = async (id) => {
        if (!confirm('Delete this media?')) return;
        try {
            await window.fetchAPI('/tour_media.php', { method: 'DELETE', body: JSON.stringify({ media_id: id }) });
            fetchMedia();
        } catch (err) { alert(err.message); }
    };

    return (
        <div style={{ background: 'rgba(255,255,255,0.03)', borderRadius: '10px', padding: '20px', border: '1px solid rgba(255,255,255,0.08)' }}>
            <h4 style={{ color: 'var(--primary-color)', marginBottom: '16px', fontSize: '0.85rem', textTransform: 'uppercase', letterSpacing: '1px' }}>
                <i className="fa-solid fa-images" style={{ marginRight: '8px' }}></i>Tour Media for: {tourTitle}
            </h4>

            {loading ? <div style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>Loading...</div> : (
                media.length === 0 ? (
                    <div style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: '16px' }}>No media yet. Upload some below.</div>
                ) : (
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: '15px', marginBottom: '20px' }}>
                        {media.map(m => (
                            <div key={m.id} style={{ position: 'relative', borderRadius: '8px', overflow: 'hidden', background: 'var(--bg-lighter)', border: '1px solid rgba(255,255,255,0.1)' }}>
                                {m.media_type === 'youtube' ? (
                                    <div style={{ padding: '10px', textAlign: 'center' }}>
                                        <i className="fa-brands fa-youtube" style={{ fontSize: '2rem', color: 'var(--primary-color)' }}></i>
                                        <div style={{ fontSize: '0.7rem', marginTop: '5px', wordBreak: 'break-all' }}>{m.media_url.substring(0, 30)}...</div>
                                    </div>
                                ) : (
                                    <img src={resolveMediaPath(m.media_url)} alt={m.title} style={{ width: '100%', height: '100px', objectFit: 'cover' }} />
                                )}
                                <div style={{ padding: '8px', fontSize: '0.8rem', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.title || 'Untitled'}</div>
                                <button onClick={() => handleDelete(m.id)} style={{ position: 'absolute', top: '5px', right: '5px', background: 'rgba(0,0,0,0.7)', border: 'none', color: 'var(--danger)', cursor: 'pointer', borderRadius: '4px', padding: '4px 6px', fontSize: '0.8rem' }} title="Delete">
                                    <i className="fa-solid fa-trash"></i>
                                </button>
                            </div>
                        ))}
                    </div>
                )
            )}

            <form onSubmit={handleAdd} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 2fr auto', gap: '10px', alignItems: 'end' }}>
                <div>
                    <label style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', display: 'block', marginBottom: '5px' }}>Title</label>
                    <input type="text" className="form-control" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} placeholder="Caption..." style={{ fontSize: '0.85rem', padding: '8px' }} />
                </div>
                <div>
                    <label style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', display: 'block', marginBottom: '5px' }}>Type</label>
                    <select className="form-control" value={form.media_type} onChange={e => setForm({ ...form, media_type: e.target.value })} style={{ fontSize: '0.85rem', padding: '8px' }}>
                        <option value="image">Image</option>
                        <option value="local_video">Local Video</option>
                        <option value="youtube">YouTube URL</option>
                    </select>
                </div>
                <div>
                    <label style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', display: 'block', marginBottom: '5px' }}>Source</label>
                    {form.media_type === 'youtube' ? (
                        <input type="url" className="form-control" required value={form.media_url} onChange={e => setForm({ ...form, media_url: e.target.value })} placeholder="https://youtube.com/..." style={{ fontSize: '0.85rem', padding: '8px' }} />
                    ) : (
                        <input type="file" className="form-control" required accept={form.media_type === 'image' ? "image/*" : "video/*"} onChange={e => setFile(e.target.files[0])} style={{ fontSize: '0.85rem', padding: '8px' }} />
                    )}
                </div>
                <button type="submit" className="btn" disabled={saving} style={{ padding: '8px 16px', fontSize: '0.85rem' }}>
                    {saving ? <i className="fa-solid fa-spinner fa-spin"></i> : <React.Fragment><i className="fa-solid fa-upload"></i> Upload</React.Fragment>}
                </button>
            </form>
        </div>
    );
}

function DealerTourRowWithAddons({ t, setPreviewTour, fetchTours, handleEditDraft }) {
    const [showAddons, setShowAddons] = useState(false);
    const [showMedia, setShowMedia] = useState(false);

    return (
        <React.Fragment>
            <tr style={{ borderBottom: (showAddons || showMedia) ? 'none' : '1px solid var(--border-color)' }}>
                <td style={{ padding: '15px', fontWeight: 'bold' }}>{t.title}</td>
                <td style={{ padding: '15px' }}>{new Date(t.start_date).toLocaleDateString()}</td>
                <td style={{ padding: '15px' }}>{t.difficulty || 3}★</td>
                <td style={{ padding: '15px' }}>
                    <span className={`badge badge-${t.status}`}>
                        {t.status}
                    </span>
                </td>
                <td style={{ padding: '15px' }}>₹{t.price}</td>
                <td style={{ padding: '15px', display: 'flex', gap: '5px', flexWrap: 'wrap' }}>
                    {t.status === 'draft' ? (
                        <button className="btn btn-secondary" style={{ padding: '5px 10px', fontSize: '0.8rem' }} onClick={() => handleEditDraft(t)}>
                            <i className="fa-solid fa-eye"></i> Preview & Submit
                        </button>
                    ) : (
                        <>
                            <button className="btn btn-secondary" style={{ padding: '5px 8px', fontSize: '0.8rem', background: showAddons ? 'var(--primary-color)' : '' }} title="Manage Add-Ons" onClick={() => { setShowAddons(!showAddons); setShowMedia(false); }}>
                                <i className="fa-solid fa-cubes-stacked"></i> Add-Ons
                            </button>
                            <button className="btn btn-secondary" style={{ padding: '5px 8px', fontSize: '0.8rem', background: showMedia ? 'var(--primary-color)' : '' }} title="Manage Media" onClick={() => { setShowMedia(!showMedia); setShowAddons(false); }}>
                                <i className="fa-solid fa-images"></i> Media
                            </button>
                        </>
                    )}
                </td>
            </tr>
            {showAddons && (
                <tr>
                    <td colSpan="6" style={{ padding: '0 15px 20px 15px', borderBottom: '1px solid var(--border-color)' }}>
                        <DealerTourAddonManager tourId={t.id} tourTitle={t.title} />
                    </td>
                </tr>
            )}
            {showMedia && (
                <tr>
                    <td colSpan="6" style={{ padding: '0 15px 20px 15px', borderBottom: '1px solid var(--border-color)' }}>
                        <DealerTourMediaManager tourId={t.id} tourTitle={t.title} />
                    </td>
                </tr>
            )}
        </React.Fragment>
    );
}

function DealerTourAddonManager({ tourId, tourTitle }) {
    const [addons, setAddons] = useState([]);
    const [loading, setLoading] = useState(false);
    const [addonForm, setAddonForm] = useState({ label: '', description: '', price: '', icon: 'fa-plus-circle' });
    const [saving, setSaving] = useState(false);

    const ICONS = ['fa-plus-circle', 'fa-camera', 'fa-bed', 'fa-utensils', 'fa-mountain', 'fa-water', 'fa-binoculars', 'fa-compass', 'fa-fire', 'fa-star', 'fa-map-location-dot', 'fa-shield-halved'];

    const fetchAddons = () => {
        setLoading(true);
        window.fetchAPI(`/tour_addons.php?tour_id=${tourId}`)
            .then(res => { setAddons(res.data || []); setLoading(false); })
            .catch(() => setLoading(false));
    };

    useEffect(() => { fetchAddons(); }, [tourId]);

    const handleAdd = async (e) => {
        e.preventDefault();
        if (!addonForm.label || !addonForm.price) return;
        setSaving(true);
        try {
            await window.fetchAPI('/tour_addons.php', {
                method: 'POST',
                body: JSON.stringify({ ...addonForm, tour_id: tourId, price: parseFloat(addonForm.price) })
            });
            setAddonForm({ label: '', description: '', price: '', icon: 'fa-plus-circle' });
            fetchAddons();
        } catch (err) { alert(err.message); }
        setSaving(false);
    };

    const handleDelete = async (addonId) => {
        if (!confirm('Delete this add-on?')) return;
        try {
            await window.fetchAPI('/tour_addons.php', { method: 'DELETE', body: JSON.stringify({ id: addonId }) });
            fetchAddons();
        } catch (err) { alert(err.message); }
    };

    return (
        <div style={{ background: 'rgba(255,255,255,0.03)', borderRadius: '10px', padding: '20px', border: '1px solid rgba(255,255,255,0.08)' }}>
            <h4 style={{ color: 'var(--primary-color)', marginBottom: '16px', fontSize: '0.85rem', textTransform: 'uppercase', letterSpacing: '1px' }}>
                <i className="fa-solid fa-cubes-stacked" style={{ marginRight: '8px' }}></i>Tour Add-Ons for: {tourTitle}
            </h4>

            {loading ? <div style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>Loading...</div> : (
                addons.length === 0 ? (
                    <div style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: '16px' }}>No add-ons yet. Add one below.</div>
                ) : (
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', marginBottom: '16px' }}>
                        {addons.map(a => (
                            <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 14px', background: 'rgba(255,255,255,0.05)', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.1)' }}>
                                <i className={`fa-solid ${a.icon}`} style={{ color: 'var(--primary-color)' }}></i>
                                <div>
                                    <div style={{ fontWeight: '600', fontSize: '0.88rem' }}>{a.label}</div>
                                    <div style={{ fontSize: '0.76rem', color: 'var(--text-muted)' }}>₹{parseFloat(a.price).toLocaleString('en-IN')}{a.description ? ' · ' + a.description : ''}</div>
                                </div>
                                <button onClick={() => handleDelete(a.id)} style={{ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', marginLeft: '6px', fontSize: '0.85rem' }} title="Delete">
                                    <i className="fa-solid fa-trash"></i>
                                </button>
                            </div>
                        ))}
                    </div>
                )
            )}

            <form onSubmit={handleAdd} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 120px 180px auto', gap: '10px', alignItems: 'end' }}>
                <div>
                    <label style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', display: 'block', marginBottom: '5px' }}>Label *</label>
                    <input type="text" className="form-control" required value={addonForm.label} onChange={e => setAddonForm({ ...addonForm, label: e.target.value })} placeholder="e.g. Photography" style={{ fontSize: '0.85rem', padding: '8px' }} />
                </div>
                <div>
                    <label style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', display: 'block', marginBottom: '5px' }}>Description</label>
                    <input type="text" className="form-control" value={addonForm.description} onChange={e => setAddonForm({ ...addonForm, description: e.target.value })} placeholder="Short desc" style={{ fontSize: '0.85rem', padding: '8px' }} />
                </div>
                <div>
                    <label style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', display: 'block', marginBottom: '5px' }}>Price (₹) *</label>
                    <input type="number" className="form-control" required min="0" value={addonForm.price} onChange={e => setAddonForm({ ...addonForm, price: e.target.value })} style={{ fontSize: '0.85rem', padding: '8px' }} />
                </div>
                <div>
                    <label style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', display: 'block', marginBottom: '5px' }}>Icon</label>
                    <select className="form-control" value={addonForm.icon} onChange={e => setAddonForm({ ...addonForm, icon: e.target.value })} style={{ fontSize: '0.85rem', padding: '8px' }}>
                        {ICONS.map(ic => <option key={ic} value={ic}>{ic.replace('fa-', '')}</option>)}
                    </select>
                </div>
                <button type="submit" className="btn" disabled={saving} style={{ padding: '8px 16px', fontSize: '0.85rem' }}>
                    {saving ? <i className="fa-solid fa-spinner fa-spin"></i> : <React.Fragment><i className="fa-solid fa-plus"></i> Add</React.Fragment>}
                </button>
            </form>
        </div>
    );
}

function DealerBlogs() {
    const [blogs, setBlogs] = useState([]);
    const [tours, setTours] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showForm, setShowForm] = useState(false);
    const [saving, setSaving] = useState(false);
    const [mediaFile, setMediaFile] = useState(null);
    const [editBlog, setEditBlog] = useState(null);

    const [formData, setFormData] = useState({ tour_id: '', title: '', excerpt: '', content: '', media_type: 'image', media_url: '', blog_url: '' });

    const fetchData = async () => {
        setLoading(true);
        try {
            const [bRes, tRes] = await Promise.all([
                window.fetchAPI('/tour_blogs.php'),
                window.fetchAPI('/dealer/tours.php')
            ]);
            setBlogs(bRes.data || []);
            setTours((tRes.data || []).filter(t => t.status === 'published' || t.status === 'approved'));
            setLoading(false);
        } catch (e) {
            console.error(e);
            setLoading(false);
        }
    };

    useEffect(() => { fetchData(); }, []);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            const body = new FormData();
            Object.keys(formData).forEach(k => {
                if (formData[k] !== null && formData[k] !== undefined) {
                    body.append(k, formData[k]);
                }
            });
            if (formData.media_type !== 'youtube' && mediaFile) {
                body.append('media_file', mediaFile);
            }

            if (editBlog) {
                body.append('blog_id', editBlog.id);
                body.append('_method', 'PUT');
                await window.fetchAPI('/tour_blogs.php', { method: 'POST', body });
            } else {
                await window.fetchAPI('/tour_blogs.php', { method: 'POST', body });
            }
            
            setShowForm(false);
            setEditBlog(null);
            setFormData({ tour_id: '', title: '', excerpt: '', content: '', media_type: 'image', media_url: '', blog_url: '' });
            setMediaFile(null);
            fetchData();
            alert(editBlog ? 'Travel Blog updated!' : 'Travel Blog submitted! It will be reviewed by Admins before becoming public.');
        } catch (err) { alert(err.message); }
        setSaving(false);
    };

    const handleEdit = (blog) => {
        setEditBlog(blog);
        setFormData({
            tour_id: blog.tour_id,
            title: blog.title,
            excerpt: blog.excerpt,
            content: blog.content || '',
            media_type: blog.media_type,
            media_url: blog.media_url || '',
            blog_url: blog.blog_url || ''
        });
        setShowForm(true);
    };

    const handleDelete = async (id) => {
        if (!confirm('Delete this blog?')) return;
        try {
            await window.fetchAPI('/tour_blogs.php', { method: 'DELETE', body: JSON.stringify({ blog_id: id }) });
            fetchData();
        } catch (err) { alert(err.message); }
    };

    if (loading) return <div>Loading...</div>;

    return (
        <div>
            <div className="d-flex justify-between align-center mb-4">
                <h2>My Travel Blogs</h2>
                <button className="btn" onClick={() => { setShowForm(!showForm); if (showForm) setEditBlog(null); }}>
                    {showForm ? 'Cancel' : <React.Fragment><i className="fa-solid fa-plus"></i> Write Travel Blog</React.Fragment>}
                </button>
            </div>

            {showForm && (
                <div className="card mb-4 p-4">
                    <h3>{editBlog ? 'Edit' : 'Write a New'} Travel Blog</h3>
                    <p className="text-muted">Share the experience of a recent tour. {editBlog ? 'Changes may require re-approval.' : 'Admin approval is required before it goes live.'}</p>
                    <form onSubmit={handleSubmit} className="mt-3">
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
                            <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                <label className="form-label">Select Associated Tour *</label>
                                <select className="form-control" required value={formData.tour_id} onChange={e => setFormData({ ...formData, tour_id: e.target.value })}>
                                    <option value="">-- Select a Tour --</option>
                                    {tours.map(t => <option key={t.id} value={t.id}>{t.title} ({new Date(t.start_date).toLocaleDateString()})</option>)}
                                </select>
                            </div>
                            <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                <label className="form-label">Blog Title *</label>
                                <input type="text" className="form-control" required value={formData.title} onChange={e => setFormData({ ...formData, title: e.target.value })} />
                            </div>
                            <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                <label className="form-label">Short Excerpt (Search/List view) *</label>
                                <textarea className="form-control" rows="2" maxLength="200" required value={formData.excerpt} onChange={e => setFormData({ ...formData, excerpt: e.target.value })} placeholder="A brief summary for the blog listing..."></textarea>
                            </div>
                            <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                <label className="form-label">Cover Media Type</label>
                                <select className="form-control" value={formData.media_type} onChange={e => setFormData({ ...formData, media_type: e.target.value })}>
                                    <option value="image">Local Image Upload</option>
                                    <option value="image_url">External Image URL</option>
                                    <option value="local_video">Local Video Upload</option>
                                    <option value="youtube">YouTube Video URL</option>
                                </select>
                            </div>
                            {formData.media_type === 'youtube' || formData.media_type === 'image_url' ? (
                                <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                    <label className="form-label">{formData.media_type === 'youtube' ? 'YouTube Link *' : 'Image URL *'}</label>
                                    <input 
                                        type="url" 
                                        className="form-control" 
                                        required 
                                        value={formData.media_url} 
                                        onChange={e => setFormData({ ...formData, media_url: e.target.value })} 
                                        placeholder={formData.media_type === 'youtube' ? "https://www.youtube.com/watch?v=..." : "https://example.com/image.jpg"} 
                                    />
                                </div>
                            ) : (
                                <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                    <label className="form-label">{formData.media_type === 'image' ? 'Cover Image File' : 'Cover Video File'} *</label>
                                    <input type="file" className="form-control" accept={formData.media_type === 'image' ? 'image/*' : 'video/*'} required onChange={e => setMediaFile(e.target.files[0])} />
                                    <small className="text-muted">Select a high-quality {formData.media_type === 'image' ? 'image' : 'video'} file for the blog cover.</small>
                                </div>
                            )}
                            <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                <label className="form-label">Full Content</label>
                                <textarea className="form-control" rows="6" value={formData.content} onChange={e => setFormData({ ...formData, content: e.target.value })} placeholder="Write the full story of this tour here..."></textarea>
                            </div>
                            <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                                <label className="form-label">External Blog Link (Optional)</label>
                                <input type="url" className="form-control" value={formData.blog_url} onChange={e => setFormData({ ...formData, blog_url: e.target.value })} placeholder="e.g. https://medium.com/@dealership/story-title" />
                                <small className="text-muted">Link to a detailed post on your official blog if available.</small>
                            </div>
                        </div>
                        <button type="submit" className="btn mt-3 w-100" disabled={saving}>{saving ? 'Saving...' : (editBlog ? 'Update Blog' : 'Submit for Review')}</button>
                    </form>
                </div>
            )}

            <div className="table-responsive">
                <table style={{ width: '100%', borderCollapse: 'collapse', backgroundColor: 'var(--bg-card)', borderRadius: '8px', overflow: 'hidden' }}>
                    <thead>
                        <tr style={{ backgroundColor: 'var(--bg-lighter)', borderBottom: '1px solid var(--border-color)', textAlign: 'left' }}>
                            <th style={{ padding: '15px' }}>Blog Info</th>
                            <th style={{ padding: '15px' }}>Associated Tour</th>
                            <th style={{ padding: '15px' }}>Status</th>
                            <th style={{ padding: '15px' }}>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {blogs.length === 0 && <tr><td colSpan="4" style={{ padding: '20px', textAlign: 'center' }}>No blogs posted yet.</td></tr>}
                        {blogs.map(b => (
                            <tr key={b.id} style={{ borderBottom: '1px solid var(--border-color)' }}>
                                <td style={{ padding: '15px', maxWidth: '300px' }}>
                                    <div style={{ fontWeight: 'bold', color: 'white' }}>{b.title}</div>
                                    <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>{b.excerpt}</div>
                                    <div style={{ fontSize: '0.8rem', color: 'var(--primary-color)' }}>{b.published_date}</div>
                                </td>
                                <td style={{ padding: '15px' }}>Tour #{b.tour_id}</td>
                                <td style={{ padding: '15px' }}>
                                    <span className={`badge badge-${b.status}`}>{b.status}</span>
                                </td>
                                <td style={{ padding: '15px', display: 'flex', gap: '5px' }}>
                                    <button className="btn btn-secondary" style={{ padding: '5px 10px', fontSize: '0.8rem' }} onClick={() => handleEdit(b)} title="Edit Blog">
                                        <i className="fa-solid fa-edit"></i> Edit
                                    </button>
                                    <button className="btn btn-secondary" style={{ padding: '5px 10px', fontSize: '0.8rem', color: 'var(--danger)' }} onClick={() => handleDelete(b.id)} title="Delete Blog">
                                        <i className="fa-solid fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

function DealerBookings() {
    const [bookings, setBookings] = useState([]);

    useEffect(() => {
        window.fetchAPI('/dealer/bookings.php')
            .then(res => setBookings(res.data))
            .catch(err => console.error(err));
    }, []);

    return (
        <div>
            <h2 className="mb-4">Tour Bookings</h2>
            <div className="table-responsive">
                <table style={{ width: '100%', borderCollapse: 'collapse', backgroundColor: 'var(--bg-card)', borderRadius: '8px', overflow: 'hidden' }}>
                    <thead>
                        <tr style={{ backgroundColor: 'var(--bg-lighter)', borderBottom: '1px solid var(--border-color)', textAlign: 'left' }}>
                            <th style={{ padding: '15px' }}>Booking ID</th>
                            <th style={{ padding: '15px' }}>Tour</th>
                            <th style={{ padding: '15px' }}>Rider</th>
                            <th style={{ padding: '15px' }}>Amount Received</th>
                            <th style={{ padding: '15px' }}>Status</th>
                            <th style={{ padding: '15px', textAlign: 'center' }}>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {bookings.map(b => (
                            <tr key={b.id} style={{ borderBottom: '1px solid var(--border-color)' }}>
                                <td style={{ padding: '15px' }}>#{b.id}</td>
                                <td style={{ padding: '15px', fontWeight: 'bold' }}>
                                    {b.tour_name}<br />
                                    <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>{new Date(b.start_date).toLocaleDateString()}</span>
                                </td>
                                <td style={{ padding: '15px' }}>
                                    {b.rider_name}<br />
                                    <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>{b.rider_email}</span><br />
                                    <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}><i className="fa-brands fa-whatsapp"></i> {b.rider_whatsapp || 'N/A'}</span>
                                </td>
                                <td style={{ padding: '15px', color: 'var(--success)' }}>₹{b.dealer_amount || 0}</td>
                                <td style={{ padding: '15px' }}>
                                    <span className={`badge badge-${b.payment_status === 'completed' ? 'approved' : 'pending'}`}>
                                        {b.payment_status}
                                    </span>
                                </td>
                                <td style={{ padding: '15px', textAlign: 'center' }}>
                                    {b.payment_status === 'completed' && b.rider_whatsapp ? (
                                        <a
                                            href={`https://wa.me/${b.rider_whatsapp.replace(/\D/g, '')}?text=${encodeURIComponent(`Hello ${b.rider_name}! Welcome to the "${b.tour_name}" tour with THROTLLR. Please join our WhatsApp group for updates: ${b.whatsapp_group_link?.includes('http') ? b.whatsapp_group_link.split(' ').filter(s => s.startsWith('http'))[0] : (b.whatsapp_group_link || 'Link will be provided soon.')}`)}`}
                                            target="_blank"
                                            rel="noreferrer"
                                            className="btn btn-outline"
                                            style={{ padding: '6px 12px', fontSize: '0.85rem', borderColor: '#25D366', color: '#25D366', display: 'inline-flex', alignItems: 'center', gap: '5px' }}
                                        >
                                            <i className="fa-brands fa-whatsapp"></i> Invite Group
                                        </a>
                                    ) : (
                                        <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>-</span>
                                    )}
                                </td>
                            </tr>
                        ))}
                        {bookings.length === 0 && (
                            <tr><td colSpan="6" style={{ padding: '30px', textAlign: 'center', color: 'var(--text-muted)' }}>No bookings found for your tours yet.</td></tr>
                        )}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

function DealerProfile({ user, setUser }) {
    const [profile, setProfile] = useState(null);
    const [loading, setLoading] = useState(true);
    const [formData, setFormData] = useState({ showroom_name: '', location: '', upi_id: '' });

    useEffect(() => {
        window.fetchAPI('/dealer/profile.php')
            .then(res => {
                setProfile(res.data);
                setFormData({ showroom_name: res.data.showroom_name, location: res.data.location, upi_id: res.data.upi_id || '' });
                setLoading(false);
            })
            .catch(err => console.error(err));
    }, []);

    const handleUpdate = async (e) => {
        e.preventDefault();
        try {
            const res = await window.fetchAPI('/dealer/profile.php', {
                method: 'PUT',
                body: JSON.stringify(formData)
            });

            // Update global user state and sessionStorage to sync UI (like sidebar)
            // res.data now contains { id, name, email, role, showroom_name, location, upi_id, balance }
            const updatedUser = {
                ...user,
                ...res.data,
                id: user.id, // Explicitly keep the User ID from the initial session
                role: res.data.role || user.role // Ensure role is preserved
            };

            console.log('Profile Sync - Updated User Object:', updatedUser);

            setUser(updatedUser);
            sessionStorage.setItem('throtllr_user', JSON.stringify(updatedUser));

            alert('Profile updated successfully!');
        } catch (err) {
            alert(err.message || 'Update failed');
        }
    }

    if (loading) return <div>Loading...</div>;

    return (
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: '30px', maxWidth: '800px' }}>
            <div>
                <h2 className="mb-4">Dealer Profile & Payment Settings</h2>
                <div className="card">
                    <div className="card-body">
                        <form onSubmit={handleUpdate}>
                            <div className="form-group">
                                <label className="form-label">Email Address (Read Only)</label>
                                <input type="text" className="form-control" value={profile.email} disabled />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Showroom Name</label>
                                <input type="text" className="form-control" value={formData.showroom_name} onChange={e => setFormData({ ...formData, showroom_name: e.target.value })} required />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Location Base</label>
                                <input type="text" className="form-control" value={formData.location} onChange={e => setFormData({ ...formData, location: e.target.value })} required />
                            </div>
                            <div className="form-group">
                                <label className="form-label">UPI ID (For Direct Rider Payments)</label>
                                <input type="text" className="form-control" value={formData.upi_id} onChange={e => setFormData({ ...formData, upi_id: e.target.value })} placeholder="e.g. showroom@bank" required />
                                <small className="text-muted">Riders will see this UPI ID when booking your tours to pay you directly. 0% Commission!</small>
                            </div>
                            <button type="submit" className="btn w-100 mt-2">Update Profile</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
}

function DealerPackages({ setPreviewTour }) {
    const navigate = useNavigate();
    const [packages, setPackages] = useState([]);
    const [loading, setLoading] = useState(true);
    const [selectedPkg, setSelectedPkg] = useState(null);
    const [startDate, setStartDate] = useState('');
    const [processingPayment, setProcessingPayment] = useState(false);
    const [showHostModal, setShowHostModal] = useState(false);
    const [coupon, setCoupon] = useState('');
    const [couponError, setCouponError] = useState('');
    const [couponSuccess, setCouponSuccess] = useState('');
    const [discountedPrice, setDiscountedPrice] = useState(null);
    const [paymentMethod, setPaymentMethod] = useState('razorpay');

    const fetchPackages = () => {
        setLoading(true);
        window.fetchAPI('/dealer/packages.php')
            .then(res => {
                setPackages(res.data);
                setLoading(false);
            })
            .catch(err => console.error(err));
    };

    useEffect(() => { fetchPackages(); }, []);

    const handleHostRequest = (pkg) => {
        setSelectedPkg(pkg);
        setShowHostModal(true);
        setCoupon('');
        setCouponError('');
        setCouponSuccess('');
        setDiscountedPrice(null);
        setPaymentMethod('razorpay');
    };

    const verifyCoupon = async () => {
        if (!coupon) return;
        setCouponError('');
        setCouponSuccess('');
        try {
            const res = await window.fetchAPI('/payments/verify_coupon.php', {
                method: 'POST',
                body: JSON.stringify({ coupon_code: coupon, package_id: selectedPkg.id })
            });
            setCouponSuccess(res.message);
            setDiscountedPrice(res.final_price);
        } catch (err) {
            setCouponError(err.message);
            setDiscountedPrice(null);
        }
    };

    const confirmHost = async (e) => {
        if (e && e.preventDefault) e.preventDefault();
        if (!startDate) return alert('Please select a start date');

        setProcessingPayment(true);
        try {
            if (paymentMethod === 'direct') {
                const packageRes = await window.fetchAPI('/dealer/packages.php', {
                    method: 'POST',
                    body: JSON.stringify({
                        package_id: selectedPkg.id,
                        start_date: startDate,
                        payment_method: 'direct'
                    })
                });

                alert('Test Booking Successful! Tour created successfully.');
                setShowHostModal(false);
                setSelectedPkg(null);
                setStartDate('');
                setProcessingPayment(false);

                if (packageRes.tour_id) {
                    setPreviewTour({ ...selectedPkg, id: packageRes.tour_id, start_date: startDate, status: 'draft' });
                    navigate('/dealer/tours');
                } else {
                    navigate('/dealer/tours');
                }
                return;
            }

            // 1. Create order
            const orderRes = await window.fetchAPI('/payments/create_package_order.php', {
                method: 'POST',
                body: JSON.stringify({ package_id: selectedPkg.id, coupon_code: couponSuccess ? coupon : '' })
            });

            if (!orderRes.success) throw new Error(orderRes.message);

            // 2. Open Razorpay Checkout
            const options = {
                key: orderRes.key,
                amount: orderRes.amount,
                currency: "INR",
                name: "THROTLLR",
                description: `Admin Booking Fee for ${selectedPkg.title}`,
                order_id: orderRes.is_mock ? undefined : orderRes.order_id,
                theme: { color: "#ff3b30" },
                handler: async function (response) {
                    try {
                        const packageRes = await window.fetchAPI('/dealer/packages.php', {
                            method: 'POST',
                            body: JSON.stringify({
                                package_id: selectedPkg.id,
                                start_date: startDate,
                                razorpay_payment_id: response.razorpay_payment_id,
                                razorpay_order_id: response.razorpay_order_id,
                                razorpay_signature: response.razorpay_signature
                            })
                        });

                        alert('Payment Successful! Now preview your tour to finalize it.');
                        setShowHostModal(false);
                        setSelectedPkg(null);
                        setStartDate('');
                        setProcessingPayment(false);

                        // Fetch the newly created tour to preview it
                        if (packageRes.tour_id) {
                            setPreviewTour({ ...selectedPkg, id: packageRes.tour_id, start_date: startDate, status: 'draft' });
                            navigate('/dealer/tours');
                        } else {
                            navigate('/dealer/tours');
                        }
                    } catch (err) {
                        alert(err.message || 'Error creating tour after payment');
                        setProcessingPayment(false);
                    }
                },
                modal: { ondismiss: function () { setProcessingPayment(false); } },
                prefill: { name: "Dealer Showroom", email: "dealer@avahan.com", contact: "9999999999" }
            };

            const rzp = new window.Razorpay(options);
            rzp.on('payment.failed', function (response) {
                alert('Payment Failed: ' + response.error.description);
                setProcessingPayment(false);
            });

            rzp.open();

        } catch (err) {
            alert(err.message || 'Error initiating payment');
            setProcessingPayment(false);
        }
    };

    if (loading) return <div>Loading available packages...</div>;

    return (
        <div>
            <h2 className="mb-4">Admin Tour Packages</h2>
            <p className="mb-4 text-muted">Select a premium tour template designed by Avahan Admin and host it for your showroom.</p>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '20px' }}>
                {packages.map(p => (
                    <div key={p.id} className="card h-100 overflow-hidden" style={{ display: 'flex', flexDirection: 'column' }}>
                        {p.image_url && <img src={p.image_url} alt={p.title} style={{ width: '100%', height: '180px', objectFit: 'cover' }} />}
                        <div className="p-4" style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
                            <div className="d-flex justify-between align-start mb-2">
                                <h3 style={{ fontSize: '1.2rem', margin: 0 }}>{p.title}</h3>
                                <span className="badge badge-approved" style={{ fontSize: '0.7rem' }}>{p.difficulty}/5 Difficulty</span>
                            </div>
                            <p style={{ fontSize: '0.9rem', color: 'var(--text-muted)', marginBottom: '15px' }}>{p.duration_days} Days &bull; {p.start_location} to {p.end_location}</p>
                            <div style={{ padding: '10px', backgroundColor: 'var(--bg-lighter)', borderRadius: '6px', marginBottom: '15px' }}>
                                <div style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>Admin Booking Fee</div>
                                <div style={{ fontWeight: 'bold' }}>₹{p.price}</div>
                            </div>
                            <div className="mt-auto">
                                <button className="btn w-100" onClick={() => handleHostRequest(p)}>Host this Tour</button>
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            {showHostModal && (
                <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.8)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }}>
                    <div className="card p-4" style={{ width: '500px', backgroundColor: '#18181b', border: '1px solid #3f3f46', position: 'relative' }}>
                        <button onClick={() => setShowHostModal(false)} style={{ position: 'absolute', top: '15px', right: '15px', background: 'none', border: 'none', color: '#a1a1aa', fontSize: '1.2rem', cursor: 'pointer' }}><i className="fa-solid fa-times"></i></button>

                        <div style={{ borderBottom: '1px solid #3f3f46', textAlign: 'center', marginBottom: '20px', paddingBottom: '20px' }}>
                            <h3 style={{ margin: 0, color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '10px' }}>
                                <i className="fa-solid fa-credit-card" style={{ color: 'var(--success)', fontSize: '1.5rem' }}></i> Host {selectedPkg.title}
                            </h3>
                            <div style={{ marginTop: '15px', fontSize: '2.5rem', fontWeight: 'bold' }}>
                                {discountedPrice !== null ? (
                                    <React.Fragment>
                                        <span style={{ textDecoration: 'line-through', color: 'var(--text-muted)', fontSize: '1.5rem', marginRight: '10px' }}>₹{selectedPkg.price}</span>
                                        <span style={{ color: 'var(--success)' }}>₹{discountedPrice}</span>
                                    </React.Fragment>
                                ) : (
                                    `₹${selectedPkg ? selectedPkg.price : ''}`
                                )}
                            </div>
                            <div style={{ color: '#a1a1aa', fontSize: '0.9rem' }}>Admin Booking Fee</div>
                        </div>

                        <form onSubmit={confirmHost}>
                            <p className="my-3" style={{ fontSize: '0.9rem', color: '#d4d4d8' }}>Choose a start date and securely process payment via Razorpay.</p>

                            <div className="form-group mb-3 text-start">
                                <label className="form-label" style={{ color: '#a1a1aa' }}>Apply Coupon (Optional)</label>
                                <div style={{ display: 'flex', gap: '10px' }}>
                                    <input type="text" className="form-control" value={coupon} onChange={e => setCoupon(e.target.value.toUpperCase())} placeholder="Enter Coupon Code" />
                                    <button type="button" className="btn btn-outline" onClick={verifyCoupon}>Apply</button>
                                </div>
                                {couponError && <div style={{ color: 'var(--danger)', fontSize: '0.8rem', marginTop: '5px', textAlign: 'left' }}>{couponError}</div>}
                                {couponSuccess && <div style={{ color: 'var(--success)', fontSize: '0.8rem', marginTop: '5px', textAlign: 'left' }}>{couponSuccess}</div>}
                            </div>

                            <div className="form-group mb-4 text-start">
                                <label className="form-label" style={{ color: '#a1a1aa' }}>Select Start Date</label>
                                <input type="date" className="form-control" value={startDate} onChange={e => setStartDate(e.target.value)} required />
                            </div>

                            <div style={{ marginTop: '20px', marginBottom: '20px', textAlign: 'left' }}>
                                <label className="form-label" style={{ color: '#a1a1aa', marginBottom: '10px', display: 'block' }}>Select Payment Method</label>
                                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '15px' }}>
                                    <div 
                                        onClick={() => setPaymentMethod('razorpay')}
                                        style={{ 
                                            padding: '10px', 
                                            borderRadius: '8px', 
                                            border: `2px solid ${paymentMethod === 'razorpay' ? 'var(--primary-color)' : 'rgba(255,255,255,0.05)'}`,
                                            backgroundColor: paymentMethod === 'razorpay' ? 'rgba(209, 18, 29, 0.1)' : 'var(--bg-lighter)',
                                            cursor: 'pointer',
                                            textAlign: 'center',
                                            transition: 'all 0.2s'
                                        }}
                                    >
                                        <i className="fa-solid fa-credit-card" style={{ fontSize: '1.2rem', marginBottom: '5px', color: paymentMethod === 'razorpay' ? 'var(--primary-color)' : 'var(--text-muted)' }}></i>
                                        <div style={{ fontWeight: 'bold', fontSize: '0.9rem', color: 'white' }}>Razorpay</div>
                                        <div style={{ fontSize: '0.65rem', color: 'var(--text-muted)' }}>Cards, UPI</div>
                                    </div>
                                    <div 
                                        onClick={() => setPaymentMethod('direct')}
                                        style={{ 
                                            padding: '10px', 
                                            borderRadius: '8px', 
                                            border: `2px solid ${paymentMethod === 'direct' ? 'var(--primary-color)' : 'rgba(255,255,255,0.05)'}`,
                                            backgroundColor: paymentMethod === 'direct' ? 'rgba(209, 18, 29, 0.1)' : 'var(--bg-lighter)',
                                            cursor: 'pointer',
                                            textAlign: 'center',
                                            transition: 'all 0.2s'
                                        }}
                                    >
                                        <i className="fa-solid fa-vial" style={{ fontSize: '1.2rem', marginBottom: '5px', color: paymentMethod === 'direct' ? 'var(--primary-color)' : 'var(--text-muted)' }}></i>
                                        <div style={{ fontWeight: 'bold', fontSize: '0.9rem', color: 'white' }}>Test Flow</div>
                                        <div style={{ fontSize: '0.65rem', color: 'var(--text-muted)' }}>Skip Payment</div>
                                    </div>
                                </div>
                            </div>

                            <button type="submit" className="btn w-100" style={{ padding: '15px', fontSize: '1.1rem', fontWeight: 'bold' }} disabled={processingPayment}>
                                {processingPayment ? 'Processing...' : (paymentMethod === 'direct' ? 'Confirm & Host (Test)' : 'Pay with Razorpay & Host')}
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
Back to Directory �������}�!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������������������������������������������������������������������� ������w�!1AQaq"2�B���� #3R�br� $4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz������������������������������������������������������������������������ ��?��_��+��?��(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(�����