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

// Check if user is admin (you may need to add admin role to users table)
if (!isset($_SESSION['user_id'])) {
    header('Location: login.html');
    exit;
}

// For now, we'll check if user is from admin. You can enhance this with proper role checking
// Add 'role' column to users table: ALTER TABLE users ADD COLUMN role ENUM('user', 'admin') DEFAULT 'user';

$user_id = $_SESSION['user_id'];

// Fetch user data
$stmt = $connection->prepare("SELECT id, name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();

// Fetch all consultations with pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$consultations_stmt = $connection->prepare("
    SELECT c.*, u.name as user_name 
    FROM consultations c 
    LEFT JOIN users u ON c.user_id = u.id 
    ORDER BY c.created_at DESC 
    LIMIT ? OFFSET ?
");
$consultations_stmt->bind_param("ii", $limit, $offset);
$consultations_stmt->execute();
$consultations_result = $consultations_stmt->get_result();
$consultations = [];
while ($row = $consultations_result->fetch_assoc()) {
    $consultations[] = $row;
}

// Get total count
$count_stmt = $connection->prepare("SELECT COUNT(*) as total FROM consultations");
$count_stmt->execute();
$count_result = $count_stmt->get_result();
$count_row = $count_result->fetch_assoc();
$total = $count_row['total'];
$pages = ceil($total / $limit);

// Handle status update via AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    $consultation_id = intval($_POST['id']);
    $new_status = trim($_POST['status']);
    
    if (in_array($new_status, ['pending', 'verified', 'scheduled', 'completed', 'cancelled'])) {
        $update_stmt = $connection->prepare("
            UPDATE consultations 
            SET status = ? 
            WHERE id = ?
        ");
        $update_stmt->bind_param("si", $new_status, $consultation_id);
        
        if ($update_stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Status updated successfully']);
            exit;
        }
    }
    
    echo json_encode(['success' => false, 'message' => 'Error updating status']);
    exit;
}

// Handle note update via AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_notes') {
    $consultation_id = intval($_POST['id']);
    $notes = trim($_POST['notes']);
    
    $update_stmt = $connection->prepare("
        UPDATE consultations 
        SET notes = ? 
        WHERE id = ?
    ");
    $update_stmt->bind_param("si", $notes, $consultation_id);
    
    if ($update_stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Notes updated successfully']);
        exit;
    }
    
    echo json_encode(['success' => false, 'message' => 'Error updating notes']);
    exit;
}

// Get statistics
$stats_stmt = $connection->prepare("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 'verified' THEN 1 ELSE 0 END) as verified,
        SUM(CASE WHEN status = 'scheduled' THEN 1 ELSE 0 END) as scheduled,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled
    FROM consultations
");
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
$stats = $stats_result->fetch_assoc();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Consultation Management - Admin Panel</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .admin-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        .admin-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

        .admin-header h1 {
            font-size: 32px;
            margin-bottom: 10px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            text-align: center;
        }

        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #667eea;
        }

        .stat-label {
            color: #666;
            font-size: 12px;
            margin-top: 5px;
        }

        .filters {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: center;
        }

        .filter-group {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .filter-group label {
            font-weight: 600;
            color: #333;
        }

        .filter-group select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .consultations-table {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        thead {
            background-color: #f8f9fa;
        }

        th {
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #333;
            border-bottom: 2px solid #e0e0e0;
        }

        td {
            padding: 15px;
            border-bottom: 1px solid #e0e0e0;
            color: #666;
        }

        tr:hover {
            background-color: #f9f9f9;
        }

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

        .status-badge.pending {
            background-color: #ffeaa7;
            color: #d63031;
        }

        .status-badge.verified {
            background-color: #74b9ff;
            color: #0984e3;
        }

        .status-badge.scheduled {
            background-color: #55efc4;
            color: #00b894;
        }

        .status-badge.completed {
            background-color: #55efc4;
            color: #00b894;
        }

        .status-badge.cancelled {
            background-color: #fab1a0;
            color: #d63031;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-view {
            background-color: #667eea;
            color: white;
        }

        .btn-view:hover {
            background-color: #5568d3;
        }

        .btn-edit {
            background-color: #3498db;
            color: white;
        }

        .btn-edit:hover {
            background-color: #2980b9;
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 50px auto;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 700px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
        }

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

        .modal-header h2 {
            color: #333;
        }

        .modal-close {
            font-size: 28px;
            font-weight: bold;
            color: #aaa;
            cursor: pointer;
        }

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

        .modal-body {
            margin-bottom: 20px;
        }

        .detail-row {
            display: grid;
            grid-template-columns: 150px 1fr;
            gap: 20px;
            padding: 10px 0;
            border-bottom: 1px solid #e0e0e0;
        }

        .detail-row:last-child {
            border-bottom: none;
        }

        .detail-label {
            font-weight: 600;
            color: #333;
        }

        .detail-value {
            color: #666;
            word-break: break-word;
        }

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

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

        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: inherit;
            font-size: 14px;
        }

        .form-group textarea {
            min-height: 100px;
            resize: vertical;
        }

        .modal-buttons {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background-color: #5568d3;
        }

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

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

        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 20px;
        }

        .pagination a,
        .pagination span {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            text-decoration: none;
            color: #667eea;
        }

        .pagination a:hover {
            background-color: #667eea;
            color: white;
        }

        .pagination .current {
            background-color: #667eea;
            color: white;
            border-color: #667eea;
        }

        @media (max-width: 768px) {
            .admin-header {
                padding: 20px;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }

            .filters {
                flex-direction: column;
                align-items: flex-start;
            }

            .filter-group {
                flex-direction: column;
                width: 100%;
            }

            .filter-group select {
                width: 100%;
            }

            table {
                font-size: 12px;
            }

            th, td {
                padding: 10px;
            }

            .modal-content {
                width: 95%;
                margin: 20px auto;
                padding: 20px;
            }

            .detail-row {
                grid-template-columns: 100px 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <div class="admin-header">
            <h1>📋 Consultation Management</h1>
            <p>Manage and track all customer consultation requests</p>
        </div>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['total'] ?? 0; ?></div>
                <div class="stat-label">Total</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #f39c12;"><?php echo $stats['pending'] ?? 0; ?></div>
                <div class="stat-label">Pending</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #3498db;"><?php echo $stats['verified'] ?? 0; ?></div>
                <div class="stat-label">Verified</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #27ae60;"><?php echo $stats['scheduled'] ?? 0; ?></div>
                <div class="stat-label">Scheduled</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #27ae60;"><?php echo $stats['completed'] ?? 0; ?></div>
                <div class="stat-label">Completed</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #e74c3c;"><?php echo $stats['cancelled'] ?? 0; ?></div>
                <div class="stat-label">Cancelled</div>
            </div>
        </div>

        <!-- Consultations Table -->
        <div class="consultations-table">
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Type</th>
                        <th>Date & Time</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($consultations as $consultation): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($consultation['first_name'] . ' ' . $consultation['last_name']); ?></strong><br>
                                <small style="color: #999;">ID: <?php echo $consultation['id']; ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($consultation['email']); ?></td>
                            <td><?php echo ucfirst(str_replace('_', ' ', htmlspecialchars($consultation['consultation_type']))); ?></td>
                            <td>
                                <?php echo date('M d, Y', strtotime($consultation['preferred_date'])); ?><br>
                                <small><?php echo date('h:i A', strtotime($consultation['preferred_time'])); ?></small>
                            </td>
                            <td>
                                <span class="status-badge <?php echo strtolower($consultation['status']); ?>">
                                    <?php echo ucfirst($consultation['status']); ?>
                                </span>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn-sm btn-view" onclick="viewConsultation(<?php echo $consultation['id']; ?>)">View</button>
                                    <button class="btn-sm btn-edit" onclick="editConsultation(<?php echo $consultation['id']; ?>)">Edit</button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($pages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?page=1">« First</a>
                    <a href="?page=<?php echo $page - 1; ?>">‹ Previous</a>
                <?php endif; ?>

                <?php for ($i = max(1, $page - 2); $i <= min($pages, $page + 2); $i++): ?>
                    <?php if ($i === $page): ?>
                        <span class="current"><?php echo $i; ?></span>
                    <?php else: ?>
                        <a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                    <?php endif; ?>
                <?php endfor; ?>

                <?php if ($page < $pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>">Next ›</a>
                    <a href="?page=<?php echo $pages; ?>">Last »</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- View Modal -->
    <div id="viewModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Consultation Details</h2>
                <span class="modal-close" onclick="closeViewModal()">&times;</span>
            </div>
            <div id="viewModalBody" class="modal-body">
                <!-- Loaded via AJAX -->
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Edit Consultation</h2>
                <span class="modal-close" onclick="closeEditModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <div class="form-group">
                        <label for="editStatus">Status</label>
                        <select id="editStatus" required>
                            <option value="pending">Pending</option>
                            <option value="verified">Verified</option>
                            <option value="scheduled">Scheduled</option>
                            <option value="completed">Completed</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="editNotes">Notes</label>
                        <textarea id="editNotes" placeholder="Add internal notes..."></textarea>
                    </div>

                    <div class="modal-buttons">
                        <button type="button" class="btn btn-secondary" onclick="closeEditModal()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        let currentConsultationId = null;

        function viewConsultation(id) {
            currentConsultationId = id;
            // In a real app, you'd fetch consultation details via AJAX
            // For now, we'll show a message
            document.getElementById('viewModalBody').innerHTML = '<p>Loading consultation details...</p>';
            document.getElementById('viewModal').style.display = 'block';
        }

        function closeViewModal() {
            document.getElementById('viewModal').style.display = 'none';
        }

        function editConsultation(id) {
            currentConsultationId = id;
            document.getElementById('editModal').style.display = 'block';
        }

        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
            document.getElementById('editForm').reset();
        }

        document.getElementById('editForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            const formData = new FormData();
            formData.append('action', 'update_status');
            formData.append('id', currentConsultationId);
            formData.append('status', document.getElementById('editStatus').value);

            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    alert('Consultation updated successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            } catch (error) {
                alert('Error updating consultation');
            }
        });

        // Close modals when clicking outside
        window.onclick = function(event) {
            const viewModal = document.getElementById('viewModal');
            const editModal = document.getElementById('editModal');

            if (event.target === viewModal) {
                viewModal.style.display = 'none';
            }
            if (event.target === editModal) {
                editModal.style.display = 'none';
            }
        }
    </script>
</body>
</html>
