<?php
/**
 * Reviews Management - Admin Page
 */

$page_title = 'Reviews';
require_once 'includes/header.php';

$message = '';
$error = '';

try {
    $pdo = getDBConnection();
    
    // Handle status updates and deletions
    if (isset($_POST['update_status'])) {
        $review_id = intval($_POST['review_id']);
        $new_status = $_POST['status'];
        $valid_statuses = ['pending', 'published', 'flagged', 'hidden'];
        
        if ($review_id > 0 && in_array($new_status, $valid_statuses)) {
            $stmt = $pdo->prepare("UPDATE reviews SET status = ? WHERE id = ?");
            $stmt->execute([$new_status, $review_id]);
            $message = "Review marked as " . htmlspecialchars($new_status);
        } else {
            $error = "Invalid review ID or status";
        }
    } elseif (isset($_POST['delete_review'])) {
        $review_id = intval($_POST['review_id']);
        
        if ($review_id > 0) {
            // Get review details before deleting to update stats
            $stmt = $pdo->prepare("SELECT vehicle_id, driver_id FROM reviews WHERE id = ?");
            $stmt->execute([$review_id]);
            $review = $stmt->fetch();
            
            $stmt = $pdo->prepare("DELETE FROM reviews WHERE id = ?");
            $stmt->execute([$review_id]);
            
            // Update vehicle stats if applicable
            if ($review && $review['vehicle_id']) {
                $stmt = $pdo->prepare("
                    UPDATE vehicles 
                    SET rating = COALESCE((SELECT AVG(vehicle_rating) FROM reviews WHERE vehicle_id = ? AND status = 'published'), 0),
                        total_reviews = (SELECT COUNT(*) FROM reviews WHERE vehicle_id = ? AND status = 'published')
                    WHERE id = ?
                ");
                $stmt->execute([$review['vehicle_id'], $review['vehicle_id'], $review['vehicle_id']]);
            }
            
            // Update driver stats if applicable
            if ($review && $review['driver_id']) {
                $stmt = $pdo->prepare("
                    UPDATE drivers 
                    SET rating = COALESCE((SELECT AVG(driver_rating) FROM reviews WHERE driver_id = ? AND status = 'published'), 0),
                        total_reviews = (SELECT COUNT(*) FROM reviews WHERE driver_id = ? AND status = 'published')
                    WHERE id = ?
                ");
                $stmt->execute([$review['driver_id'], $review['driver_id'], $review['driver_id']]);
            }
            
            $message = "Review deleted successfully!";
        } else {
            $error = "Invalid review ID";
        }
    } elseif (isset($_POST['bulk_action']) && !empty($_POST['bulk_action'])) {
        $bulk_action = $_POST['bulk_action'];
        $valid_bulk_actions = ['approve', 'flag', 'delete'];
        
        if (in_array($bulk_action, $valid_bulk_actions) && !empty($_POST['selected_reviews'])) {
            $selected_ids = array_map('intval', $_POST['selected_reviews']);
            $selected_ids = array_filter($selected_ids); // Remove any zeros
            
            if (!empty($selected_ids)) {
                $placeholders = implode(',', array_fill(0, count($selected_ids), '?'));
                
                if ($bulk_action === 'approve') {
                    $stmt = $pdo->prepare("UPDATE reviews SET status = 'published' WHERE id IN ($placeholders)");
                    $stmt->execute($selected_ids);
                    $message = count($selected_ids) . " reviews approved!";
                } elseif ($bulk_action === 'flag') {
                    $stmt = $pdo->prepare("UPDATE reviews SET status = 'flagged' WHERE id IN ($placeholders)");
                    $stmt->execute($selected_ids);
                    $message = count($selected_ids) . " reviews flagged!";
                } elseif ($bulk_action === 'delete') {
                    // Get affected vehicles and drivers for stats update
                    $stmt = $pdo->prepare("SELECT vehicle_id, driver_id FROM reviews WHERE id IN ($placeholders)");
                    $stmt->execute($selected_ids);
                    $affected_reviews = $stmt->fetchAll();
                    
                    $vehicle_ids = [];
                    $driver_ids = [];
                    foreach ($affected_reviews as $r) {
                        if ($r['vehicle_id']) $vehicle_ids[] = $r['vehicle_id'];
                        if ($r['driver_id']) $driver_ids[] = $r['driver_id'];
                    }
                    $vehicle_ids = array_unique($vehicle_ids);
                    $driver_ids = array_unique($driver_ids);
                    
                    $stmt = $pdo->prepare("DELETE FROM reviews WHERE id IN ($placeholders)");
                    $stmt->execute($selected_ids);
                    
                    // Update stats for affected vehicles
                    foreach ($vehicle_ids as $vid) {
                        $stmt = $pdo->prepare("
                            UPDATE vehicles 
                            SET rating = COALESCE((SELECT AVG(vehicle_rating) FROM reviews WHERE vehicle_id = ? AND status = 'published'), 0),
                                total_reviews = (SELECT COUNT(*) FROM reviews WHERE vehicle_id = ? AND status = 'published')
                            WHERE id = ?
                        ");
                        $stmt->execute([$vid, $vid, $vid]);
                    }
                    
                    // Update stats for affected drivers
                    foreach ($driver_ids as $did) {
                        $stmt = $pdo->prepare("
                            UPDATE drivers 
                            SET rating = COALESCE((SELECT AVG(driver_rating) FROM reviews WHERE driver_id = ? AND status = 'published'), 0),
                                total_reviews = (SELECT COUNT(*) FROM reviews WHERE driver_id = ? AND status = 'published')
                            WHERE id = ?
                        ");
                        $stmt->execute([$did, $did, $did]);
                    }
                    
                    $message = count($selected_ids) . " reviews deleted!";
                }
            }
        }
    }

    // Filter by driver if specified
    $driver_filter = isset($_GET['driver_id']) ? intval($_GET['driver_id']) : null;
    
    // Get reviews with stats
    $query = "SELECT r.*, u.first_name, u.last_name, v.make, v.model, d.first_name as driver_first_name, d.last_name as driver_last_name 
              FROM reviews r 
              LEFT JOIN users u ON r.user_id = u.id 
              LEFT JOIN vehicles v ON r.vehicle_id = v.id 
              LEFT JOIN drivers d ON r.driver_id = d.id";
    
    if ($driver_filter) {
        $query .= " WHERE r.driver_id = " . $driver_filter;
    }
    
    $query .= " ORDER BY r.created_at DESC";
    
    $stmt = $pdo->query($query);
    $reviews = $stmt->fetchAll();
    
    // Get review stats
    $stmt = $pdo->query("SELECT status, COUNT(*) as count FROM reviews GROUP BY status");
    $review_stats = [];
    while ($row = $stmt->fetch()) {
        $review_stats[$row['status']] = $row['count'];
    }

} catch (PDOException $e) {
    $reviews = [];
    $review_stats = ['pending' => 0, 'published' => 0, 'flagged' => 0, 'hidden' => 0];
    $error = "Database error: " . $e->getMessage();
}
?>

<div class="flex h-screen overflow-hidden">
    <?php include 'includes/sidebar.php'; ?>
    
    <div class="flex-1 flex flex-col overflow-hidden">
        <header class="sticky top-0 z-30 flex items-center bg-white/80 dark:bg-background-dark/80 backdrop-blur-md p-4 justify-between border-b border-slate-200 dark:border-slate-800 lg:px-8">
            <div class="flex items-center gap-4">
                <h2 class="text-slate-900 dark:text-white text-clamp-lg font-bold">
                    <?= $driver_filter ? 'Driver Reviews' : 'Review Moderation' ?>
                </h2>
                <?php if ($driver_filter): ?>
                    <a href="reviews.php" class="text-sm text-primary hover:underline flex items-center gap-1">
                        <span class="material-symbols-outlined text-sm">close</span>
                        Clear Filter
                    </a>
                <?php endif; ?>
            </div>
        </header>

        <main class="flex-1 overflow-y-auto p-4 lg:p-8 pb-24 admin-content">
            <!-- Review Stats -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-white dark:bg-surface-dark rounded-xl p-4 border border-slate-200 dark:border-slate-800 shadow-sm">
                    <p class="text-xs text-slate-500 font-medium uppercase tracking-wider">Pending</p>
                    <p class="text-clamp-2xl font-bold text-orange-500"><?= $review_stats['pending'] ?? 0 ?></p>
                </div>
                <div class="bg-white dark:bg-surface-dark rounded-xl p-4 border border-slate-200 dark:border-slate-800 shadow-sm">
                    <p class="text-xs text-slate-500 font-medium uppercase tracking-wider">Published</p>
                    <p class="text-clamp-2xl font-bold text-emerald-500"><?= $review_stats['published'] ?? 0 ?></p>
                </div>
                <div class="bg-white dark:bg-surface-dark rounded-xl p-4 border border-slate-200 dark:border-slate-800 shadow-sm">
                    <p class="text-xs text-slate-500 font-medium uppercase tracking-wider">Flagged</p>
                    <p class="text-clamp-2xl font-bold text-red-500"><?= $review_stats['flagged'] ?? 0 ?></p>
                </div>
                <div class="bg-white dark:bg-surface-dark rounded-xl p-4 border border-slate-200 dark:border-slate-800 shadow-sm">
                    <p class="text-xs text-slate-500 font-medium uppercase tracking-wider">Total Reviews</p>
                    <p class="text-clamp-2xl font-bold text-primary"><?= array_sum($review_stats) ?></p>
                </div>
            </div>

            <!-- Bulk Actions -->
            <?php if (!empty($reviews)): ?>
                <div class="bg-white dark:bg-surface-dark rounded-xl border border-slate-200 dark:border-slate-800 p-4 mb-6 shadow-sm">
                    <form id="bulkActionsForm" method="POST" class="flex items-center gap-4">
                        <input type="hidden" name="bulk_action" value="">
                        <select name="bulk_action_type" id="bulkActionSelect" class="px-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg text-sm font-bold bg-transparent dark:bg-slate-900 dark:text-white">
                            <option value="">Bulk Actions</option>
                            <option value="approve">Approve Selected</option>
                            <option value="flag">Flag Selected</option>
                            <option value="delete">Delete Selected</option>
                        </select>
                        <button type="submit" onclick="return validateBulkAction()" class="bg-primary text-white px-4 py-2 rounded-lg text-sm font-bold cursor-pointer">
                            Apply
                        </button>
                    </form>
                </div>
                <script>
                    function validateBulkAction() {
                        const action = document.getElementById('bulkActionSelect').value;
                        if (!action) {
                            alert('Please select a bulk action');
                            return false;
                        }
                        const checkboxes = document.querySelectorAll('input[name="selected_reviews[]"]:checked');
                        if (checkboxes.length === 0) {
                            alert('Please select at least one review');
                            return false;
                        }
                        document.getElementById('bulkActionsForm').querySelector('input[name="bulk_action"]').value = action;
                        return confirm('Are you sure you want to ' + action + ' ' + checkboxes.length + ' review(s)?');
                    }
                </script>
            <?php endif; ?>

            <div class="grid grid-cols-1 xl:grid-cols-2 4xl:grid-cols-3 6xl:grid-cols-4 8xl:grid-cols-6 gap-6">
                <?php if (empty($reviews)): ?>
                    <div class="bg-white dark:bg-surface-dark rounded-2xl border border-slate-200 dark:border-slate-800 p-12 text-center shadow-sm">
                        <span class="material-symbols-outlined text-6xl text-slate-300 dark:text-slate-700 mb-4">rate_review</span>
                        <h3 class="text-lg font-bold text-slate-900 dark:text-white mb-2">No reviews found</h3>
                        <p class="text-slate-500">There are no customer reviews in the database yet.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($reviews as $r): ?>
                        <div class="bg-white dark:bg-surface-dark rounded-2xl border border-slate-200 dark:border-slate-800 p-6 shadow-sm mb-4">
                            <div class="flex justify-between items-start mb-4">
                                <div class="flex items-center gap-3">
                                    <input type="checkbox" name="selected_reviews[]" value="<?= $r['id'] ?>" form="bulkActionsForm" class="rounded cursor-pointer">
                                    <div class="size-10 rounded-full bg-primary/10 flex items-center justify-center font-bold text-primary">
                                        <?= substr($r['first_name'] ?? 'U', 0, 1) ?>
                                    </div>
                                    <div>
                                        <h4 class="font-bold text-sm"><?= htmlspecialchars(($r['first_name'] ?? 'User') . ' ' . ($r['last_name'] ?? '')) ?></h4>
                                        <p class="text-xs text-slate-500">
                                            <?= htmlspecialchars(($r['make'] ?? 'Unknown') . ' ' . ($r['model'] ?? '')) ?>
                                            <?php if ($r['driver_first_name']): ?>
                                                with <?= htmlspecialchars($r['driver_first_name'] . ' ' . $r['driver_last_name']) ?>
                                            <?php endif; ?>
                                            • <?= date('M d, Y', strtotime($r['created_at'])) ?>
                                        </p>
                                    </div>
                                </div>
                                <div class="flex flex-col items-end gap-1">
                                    <div class="flex items-center gap-1 text-amber-500 font-bold">
                                        <span class="material-symbols-outlined text-sm fill-1">star</span>
                                        <?= number_format($r['overall_rating'], 1) ?>
                                    </div>
                                    <span class="text-[10px] px-2 py-0.5 rounded-full <?= $r['status'] === 'published' ? 'bg-emerald-100 text-emerald-700' : ($r['status'] === 'flagged' ? 'bg-red-100 text-red-700' : 'bg-orange-100 text-orange-700') ?>">
                                        <?= ucfirst($r['status']) ?>
                                    </span>
                                </div>
                            </div>
                            <div class="space-y-3 mb-6">
                                <?php if ($r['vehicle_comment']): ?>
                                    <div class="flex gap-2">
                                        <span class="material-symbols-outlined text-sm text-slate-400">directions_car</span>
                                        <p class="text-sm text-slate-600 dark:text-slate-400 italic">"<?= htmlspecialchars($r['vehicle_comment']) ?>"</p>
                                    </div>
                                <?php endif; ?>
                                <?php if ($r['driver_comment']): ?>
                                    <div class="flex gap-2">
                                        <span class="material-symbols-outlined text-sm text-slate-400">person</span>
                                        <p class="text-sm text-slate-600 dark:text-slate-400 italic">"<?= htmlspecialchars($r['driver_comment']) ?>"</p>
                                    </div>
                                <?php endif; ?>
                                <?php if ($r['service_comment']): ?>
                                    <div class="flex gap-2">
                                        <span class="material-symbols-outlined text-sm text-slate-400">business</span>
                                        <p class="text-sm text-slate-600 dark:text-slate-400 italic">"<?= htmlspecialchars($r['service_comment']) ?>"</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="flex gap-2">
                                <?php if ($r['status'] !== 'published'): ?>
                                    <form method="POST" class="inline">
                                        <input type="hidden" name="review_id" value="<?= $r['id'] ?>">
                                        <button type="submit" name="update_status" value="published" class="px-4 py-2 bg-emerald-500 text-white text-xs font-bold rounded-lg cursor-pointer">Publish</button>
                                    </form>
                                <?php endif; ?>
                                
                                <?php if ($r['status'] !== 'flagged'): ?>
                                    <form method="POST" class="inline">
                                        <input type="hidden" name="review_id" value="<?= $r['id'] ?>">
                                        <button type="submit" name="update_status" value="flagged" class="px-4 py-2 bg-orange-500 text-white text-xs font-bold rounded-lg cursor-pointer">Flag</button>
                                    </form>
                                <?php endif; ?>
                                
                                <form method="POST" class="inline">
                                    <input type="hidden" name="review_id" value="<?= $r['id'] ?>">
                                    <button type="submit" name="delete_review" onclick="return confirm('Delete this review?')" class="px-4 py-2 text-rose-500 text-xs font-bold rounded-lg hover:bg-rose-500/10 cursor-pointer">Delete</button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </main>
    </div>
</div>

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