<?php
require_once '../config.php';
header('Content-Type: application/json');

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'get-pending') {
    // Fetch pending reviews
    $status = $_GET['status'] ?? 'pending';
    
    if ($status === 'all') {
        $query = "SELECT id, customer_id, customer_name, rating, comment, status, created_at 
                  FROM reviews 
                  ORDER BY created_at DESC 
                  LIMIT 100";
    } else {
        $query = "SELECT id, customer_id, customer_name, rating, comment, status, created_at 
                  FROM reviews 
                  WHERE status = ? 
                  ORDER BY created_at DESC 
                  LIMIT 100";
    }
    
    if ($status !== 'all') {
        $stmt = $conn->prepare($query);
        $stmt->bind_param('s', $status);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $result = $conn->query($query);
    }
    
    $reviews = [];
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $reviews[] = $row;
        }
    }
    
    // Get counts for each status
    $pendingCount = $conn->query("SELECT COUNT(*) as count FROM reviews WHERE status='pending'")->fetch_assoc()['count'];
    $approvedCount = $conn->query("SELECT COUNT(*) as count FROM reviews WHERE status='approved'")->fetch_assoc()['count'];
    $rejectedCount = $conn->query("SELECT COUNT(*) as count FROM reviews WHERE status='rejected'")->fetch_assoc()['count'];
    
    echo json_encode([
        'success' => true,
        'reviews' => $reviews,
        'counts' => [
            'pending' => $pendingCount,
            'approved' => $approvedCount,
            'rejected' => $rejectedCount
        ]
    ]);
    exit;
}

if ($action === 'approve') {
    $reviewId = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    
    if ($reviewId <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid review ID']);
        exit;
    }
    
    $stmt = $conn->prepare("UPDATE reviews SET status = 'approved' WHERE id = ?");
    $stmt->bind_param('i', $reviewId);
    $success = $stmt->execute();
    $stmt->close();
    
    if ($success) {
        echo json_encode(['success' => true, 'message' => 'Review approved successfully']);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to approve review']);
    }
    exit;
}

if ($action === 'reject') {
    $reviewId = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    
    if ($reviewId <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid review ID']);
        exit;
    }
    
    $stmt = $conn->prepare("UPDATE reviews SET status = 'rejected' WHERE id = ?");
    $stmt->bind_param('i', $reviewId);
    $success = $stmt->execute();
    $stmt->close();
    
    if ($success) {
        echo json_encode(['success' => true, 'message' => 'Review rejected successfully']);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to reject review']);
    }
    exit;
}

if ($action === 'remove') {
    $reviewId = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    
    if ($reviewId <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid review ID']);
        exit;
    }
    
    $stmt = $conn->prepare("DELETE FROM reviews WHERE id = ?");
    $stmt->bind_param('i', $reviewId);
    $success = $stmt->execute();
    $stmt->close();
    
    if ($success) {
        echo json_encode(['success' => true, 'message' => 'Review removed successfully']);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to remove review']);
    }
    exit;
}

http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Invalid action']);
?>
