<?php
session_start();
require_once __DIR__ . '/config/db.php';

// Check if customer is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'customer') {
    header('Location: login.php');
    exit;
}

$page_title = 'Customer Dashboard — Interior Design';
$customer_id = $_SESSION['user_id'];
$customer_name = $_SESSION['user_name'];
$customer_email = $_SESSION['user_email'];

// Get customer's orders
$orders_query = "SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC LIMIT 10";
$stmt = $conn->prepare($orders_query);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$orders_result = $stmt->get_result();
$orders = $orders_result->fetch_all(MYSQLI_ASSOC);
$total_orders = count($orders);

?>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'DM Sans', sans-serif;
            background: linear-gradient(135deg, #f5f5f5 0%, #efefef 100%);
            min-height: 100vh;
        }

        .customer-dashboard {
            min-height: calc(100vh - 300px);
            padding: 40px 20px;
        }

        .dashboard-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        /* HEADER */
        .dashboard-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 40px;
            flex-wrap: wrap;
            gap: 20px;
            background: #d4a33a;
            padding: 30px;
            border-radius: 14px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .dashboard-title h1 {
            font-size: 32px;
            color: #1a1a1a;
            margin-bottom: 8px;
        }

        .dashboard-title p {
            color: #666;
            font-size: 14px;
        }

        .customer-profile {
            display: flex;
            align-items: center;
            gap: 16px;
            background: linear-gradient(135deg, #d4a33a, #b8905a);
            padding: 16px 24px;
            border-radius: 10px;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .customer-profile:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(212, 163, 58, 0.3);
        }

        .customer-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 20px;
            border: 2px solid white;
        }

        .customer-info h3 {
            font-size: 16px;
            margin-bottom: 4px;
        }

        .customer-info p {
            font-size: 12px;
            opacity: 0.9;
        }

        /* TABS */
        .dashboard-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
            border-bottom: 2px solid #e0e0e0;
            background: white;
            padding: 0 30px;
            border-radius: 14px 14px 0 0;
            flex-wrap: wrap;
        }

        .tab-button {
            padding: 16px 24px;
            background: none;
            border: none;
            cursor: pointer;
            font-weight: 600;
            color: #999;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
            font-size: 14px;
        }

        .tab-button.active {
            color: #d4a33a;
            border-bottom-color: #d4a33a;
        }

        .tab-button:hover {
            color: #d4a33a;
        }

        /* TAB CONTENT */
        .tab-content {
            display: none;
            background: white;
            padding: 30px;
            border-radius: 0 0 14px 14px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .tab-content.active {
            display: block;
        }

        /* ORDERS TABLE */
        .orders-table {
            width: 100%;
            border-collapse: collapse;
        }

        .orders-table thead {
            background: #f9f9f9;
            border-bottom: 2px solid #e0e0e0;
        }

        .orders-table th {
            padding: 16px;
            text-align: left;
            font-weight: 700;
            color: #333;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .orders-table td {
            padding: 16px;
            border-bottom: 1px solid #e0e0e0;
            color: #666;
            font-size: 14px;
        }

        .orders-table tbody tr:hover {
            background: #f9f9f9;
        }

        .order-status {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-processing {
            background: #cfe2ff;
            color: #084298;
        }

        .status-completed {
            background: #d1e7dd;
            color: #0f5132;
        }

        .status-cancelled {
            background: #f8d7da;
            color: #842029;
        }

        .no-data {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        /* PROFILE FORM */
        .profile-form {
            max-width: 600px;
        }

        .form-group {
            margin-bottom: 24px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
            font-size: 14px;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-family: 'DM Sans', sans-serif;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #d4a33a;
            box-shadow: 0 0 0 3px rgba(212, 163, 58, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .form-divider {
            border-top: 2px solid #e0e0e0;
            margin: 32px 0;
        }

        .form-actions {
            display: flex;
            gap: 16px;
            flex-wrap: wrap;
            margin-top: 32px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: linear-gradient(135deg, #d4a33a, #b8905a);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(212, 163, 58, 0.3);
        }

        .btn-secondary {
            background: #e0e0e0;
            color: #333;
        }

        .btn-secondary:hover {
            background: #d0d0d0;
        }

        .message {
            padding: 16px;
            border-radius: 8px;
            margin-bottom: 24px;
            font-size: 14px;
        }

        .message.success {
            background: #d1e7dd;
            color: #0f5132;
            border-left: 4px solid #198754;
        }

        .message.error {
            background: #f8d7da;
            color: #842029;
            border-left: 4px solid #dc3545;
        }

        /* STATS GRID */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 24px;
            margin-bottom: 40px;
        }

        .stat-card {
            background: white;
            padding: 28px;
            border-radius: 14px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            border-top: 4px solid #d4a33a;
            transition: all 0.3s ease;
            text-align: center;
        }

        .stat-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 12px 28px rgba(0, 0, 0, 0.15);
        }

        .stat-icon {
            font-size: 36px;
            color: #d4a33a;
            margin-bottom: 12px;
        }

        .stat-label {
            font-size: 13px;
            color: #999;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 8px;
            font-weight: 600;
        }

        .stat-value {
            font-size: 32px;
            color: #1a1a1a;
            font-weight: 700;
        }

        /* CONTENT CARDS */
        .content-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 24px;
            margin-bottom: 40px;
        }

        .content-card {
            background: white;
            padding: 28px;
            border-radius: 14px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .content-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 12px 28px rgba(0, 0, 0, 0.15);
        }

        .content-card h3 {
            font-size: 18px;
            color: #1a1a1a;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .content-card i {
            color: #d4a33a;
            font-size: 20px;
        }

        .content-card p {
            color: #666;
            font-size: 14px;
            line-height: 1.8;
            margin-bottom: 16px;
        }

        .card-action {
            display: inline-block;
            padding: 10px 20px;
            background: linear-gradient(135deg, #d4a33a, #b8905a);
            color: white;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.3s ease;
        }

        .card-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(212, 163, 58, 0.3);
        }

        /* MODAL */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: white;
            padding: 40px;
            border-radius: 14px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 500px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            border-bottom: 2px solid #e0e0e0;
            padding-bottom: 16px;
        }

        .modal-header h2 {
            font-size: 24px;
            color: #1a1a1a;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #999;
            transition: color 0.3s ease;
        }

        .modal-close:hover {
            color: #333;
        }

        /* LOGOUT BUTTON */
        .logout-section {
            text-align: center;
            padding: 20px;
            margin-top: 40px;
        }

        .logout-btn {
            padding: 14px 36px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .logout-btn:hover {
            background: #c82333;
            transform: translateY(-2px);
        }

        /* RESPONSIVE */
        @media (max-width: 768px) {
            .customer-dashboard {
                padding: 20px;
            }

            .dashboard-header {
                flex-direction: column;
                text-align: center;
            }

            .dashboard-title h1 {
                font-size: 24px;
            }

            .customer-profile {
                justify-content: center;
                width: 100%;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .content-grid {
                grid-template-columns: 1fr;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .orders-table {
                font-size: 12px;
            }

            .orders-table th,
            .orders-table td {
                padding: 12px 8px;
            }

            .modal-content {
                padding: 24px;
            }
        }
    </style>

    

    <div class="customer-dashboard">
        <div class="dashboard-container">
            <!-- HEADER -->
            <div class="dashboard-header">
                <div class="dashboard-title">
                    <h1>Welcome, <?php echo htmlspecialchars($customer_name); ?>! 🏡</h1>
                    <p><?php echo date('l, F j, Y'); ?></p>
                </div>
                <div class="customer-profile" onclick="openProfileModal()">
                    <div class="customer-avatar"><?php echo strtoupper(substr($customer_name, 0, 1)); ?></div>
                    <div class="customer-info">
                        <h3><?php echo htmlspecialchars($customer_name); ?></h3>
                        <p>View Profile →</p>
                    </div>
                </div>
            </div>

            <!-- STATISTICS -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-shopping-bag"></i></div>
                    <div class="stat-label">Total Orders</div>
                    <div class="stat-value"><?php echo $total_orders; ?></div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-clock"></i></div>
                    <div class="stat-label">Pending Orders</div>
                    <div class="stat-value"><?php echo count(array_filter($orders, function($o) { return $o['status'] === 'pending'; })); ?></div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
                    <div class="stat-label">Completed Orders</div>
                    <div class="stat-value"><?php echo count(array_filter($orders, function($o) { return $o['status'] === 'completed'; })); ?></div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-calendar"></i></div>
                    <div class="stat-label">Scheduled Consultations</div>
                    <div class="stat-value">0</div>
                </div>
            </div>

            <!-- QUICK ACTIONS -->
            <div class="content-grid">
                <div class="content-card" onclick="switchTab('orders')">
                    <h3><i class="fas fa-shopping-bag"></i> View Orders</h3>
                    <p>Track all your orders and their delivery status in real-time.</p>
                    <a href="#" onclick="event.preventDefault(); switchTab('orders');" class="card-action">View Orders →</a>
                </div>

                <div class="content-card" onclick="openConsultationPage()">
                    <h3><i class="fas fa-calendar"></i> Schedule Consultation</h3>
                    <p>Book an appointment with our design team for your project.</p>
                    <a href="consul.p" onclick="event.preventDefault(); openConsultationPage();" class="card-action">Schedule Now →</a>
                </div>

                <div class="content-card" onclick="switchTab('profile')">
                    <h3><i class="fas fa-user"></i> Edit Profile</h3>
                    <p>Update your personal information and password.</p>
                    <a href="#" onclick="event.preventDefault(); switchTab('profile');" class="card-action">Edit Profile →</a>
                </div>
            </div>

            <!-- TABS -->
            <div class="dashboard-tabs">
                <button class="tab-button active" onclick="switchTab('overview')">Overview</button>
                <button class="tab-button" onclick="switchTab('orders')">Orders</button>
                <button class="tab-button" onclick="switchTab('profile')">Profile</button>
            </div>

            <!-- TAB: OVERVIEW -->
            <div id="tab-overview" class="tab-content active">
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon"><i class="fas fa-lightbulb"></i></div>
                        <div class="stat-label">Quick Tips</div>
                        <p style="color: #666; margin-top: 12px;">💡 Track your orders in real-time, schedule consultations, and update your profile information anytime.</p>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon"><i class="fas fa-headset"></i></div>
                        <div class="stat-label">Need Help?</div>
                        <p style="color: #666; margin-top: 12px;">📞 Contact our support team at any time. We're here to help with all your questions.</p>
                    </div>
                </div>
            </div>

            <!-- TAB: ORDERS -->
            <div id="tab-orders" class="tab-content">
                <h2 style="margin-bottom: 20px; color: #1a1a1a;">Your Orders</h2>
                <?php if (!empty($orders)): ?>
                    <div style="overflow-x: auto;">
                        <table class="orders-table">
                            <thead>
                                <tr>
                                    <th>Order ID</th>
                                    <th>Date</th>
                                    <th>Total Amount</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($orders as $order): ?>
                                    <tr>
                                        <td><strong>#<?php echo htmlspecialchars($order['id']); ?></strong></td>
                                        <td><?php echo date('M d, Y', strtotime($order['created_at'])); ?></td>
                                        <td>Rs. <?php echo number_format($order['total_amount'], 0); ?></td>
                                        <td>
                                            <span class="order-status status-<?php echo strtolower($order['status']); ?>">
                                                <?php echo ucfirst($order['status']); ?>
                                            </span>
                                        </td>
                                        <td><a href="order-details.php?id=<?php echo $order['id']; ?>" class="card-action" style="padding: 6px 12px; font-size: 12px;">View</a></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <div class="no-data">
                        <i class="fas fa-inbox" style="font-size: 48px; color: #ddd; margin-bottom: 16px;"></i>
                        <p>You haven't placed any orders yet.</p>
                        <a href="../shop.php" class="card-action" style="margin-top: 16px;">Start Shopping →</a>
                    </div>
                <?php endif; ?>
            </div>

            <!-- TAB: PROFILE -->
            <div id="tab-profile" class="tab-content">
                <h2 style="margin-bottom: 20px; color: #1a1a1a;">Edit Your Profile</h2>
                <form id="profileForm" class="profile-form">
                    <div id="profileMessage"></div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>First Name</label>
                            <input type="text" id="firstName" name="first_name" placeholder="Enter your first name">
                        </div>
                        <div class="form-group">
                            <label>Last Name</label>
                            <input type="text" id="lastName" name="last_name" placeholder="Enter your last name">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Email Address</label>
                        <input type="email" id="email" name="email" placeholder="Enter your email" readonly style="background: #f5f5f5;">
                    </div>

                    <div class="form-group">
                        <label>Phone Number</label>
                        <input type="tel" id="phone" name="phone" placeholder="Enter your phone number">
                    </div>

                    <div class="form-group">
                        <label>Address</label>
                        <textarea id="address" name="address" placeholder="Enter your address" rows="3"></textarea>
                    </div>

                    <div class="form-divider"></div>

                    <h3 style="font-size: 18px; color: #1a1a1a; margin-bottom: 16px;">Change Password</h3>

                    <div class="form-group">
                        <label>Current Password</label>
                        <input type="password" id="currentPassword" name="current_password" placeholder="Enter your current password">
                    </div>

                    <div class="form-group">
                        <label>New Password</label>
                        <input type="password" id="newPassword" name="new_password" placeholder="Enter new password">
                    </div>

                    <div class="form-group">
                        <label>Confirm New Password</label>
                        <input type="password" id="confirmPassword" name="confirm_password" placeholder="Confirm new password">
                    </div>

                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                        <button type="button" class="btn btn-secondary" onclick="resetProfileForm()">Reset</button>
                    </div>
                </form>
            </div>

            <!-- LOGOUT -->
            <div class="logout-section">
                <a href="logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </div>
    </div>

    <!-- PROFILE MODAL -->
    <div id="profileModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Profile Information</h2>
                <button class="modal-close" onclick="closeProfileModal()">×</button>
            </div>
            <div id="modalProfileContent">
                <p>Loading...</p>
            </div>
        </div>
    </div>

    <script>
        // Load customer profile data on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadProfileData();
        });

        function switchTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Deactivate all buttons
            document.querySelectorAll('.tab-button').forEach(btn => {
                btn.classList.remove('active');
            });

            // Show selected tab
            const selectedTab = document.getElementById('tab-' + tabName);
            if (selectedTab) {
                selectedTab.classList.add('active');
            }

            // Activate selected button
            event.target.classList.add('active');
        }

        function loadProfileData() {
            const nameParts = '<?php echo htmlspecialchars($customer_name); ?>'.split(' ');
            document.getElementById('firstName').value = nameParts[0] || '';
            document.getElementById('lastName').value = nameParts.slice(1).join(' ') || '';
            document.getElementById('email').value = '<?php echo htmlspecialchars($customer_email); ?>';
        }

        function resetProfileForm() {
            loadProfileData();
            document.getElementById('currentPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
        }

        document.getElementById('profileForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const formData = new FormData(this);
            const messageDiv = document.getElementById('profileMessage');

            try {
                const response = await fetch('api/update-profile.php', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    messageDiv.innerHTML = '<div class="message success">✅ ' + data.message + '</div>';
                    if (data.redirect) {
                        setTimeout(() => location.href = data.redirect, 2000);
                    }
                } else {
                    messageDiv.innerHTML = '<div class="message error">❌ ' + data.message + '</div>';
                }
            } catch (error) {
                messageDiv.innerHTML = '<div class="message error">❌ Error: ' + error.message + '</div>';
            }
        });

        function openProfileModal() {
            document.getElementById('profileModal').classList.add('active');
        }

        function closeProfileModal() {
            document.getElementById('profileModal').classList.remove('active');
        }

        function openConsultationPage() {
            window.location.href = 'consultation.php';
        }

        // Close modal when clicking outside
        document.getElementById('profileModal')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closeProfileModal();
            }
        });
    </script>

<?php
include 'footer.php';
?>
