<?php

session_start();

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: admin_login.php");
    exit;
}

if (isset($_GET['logout'])) {
    session_destroy();
    header("location: admin_login.php");
    exit;
}

require_once '../config.php';
require_once '../get_setting.php';


// --- PAGINATION FOR REVIEWS ---
$reviews_per_page = 6;
$total_reviews_sql = "SELECT COUNT(id) FROM winners";
$total_reviews_stmt = $pdo->query($total_reviews_sql);
$total_reviews_count = $total_reviews_stmt->fetchColumn();
$total_review_pages = ceil($total_reviews_count / $reviews_per_page);

$review_page = isset($_GET['rpage']) && is_numeric($_GET['rpage']) ? (int)$_GET['rpage'] : 1;
if ($review_page > $total_review_pages && $total_review_pages > 0) $review_page = $total_review_pages;
if ($review_page < 1) $review_page = 1;
$review_offset = ($review_page - 1) * $reviews_per_page;

$prizes = [];
$sql = "SELECT id, winner_name, winner_location, prize_won, winner_image_path, created_at FROM winners ORDER BY id DESC LIMIT :limit OFFSET :offset";
if ($stmt = $pdo->prepare($sql)) {
    $stmt->bindValue(':limit', (int) $reviews_per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', (int) $review_offset, PDO::PARAM_INT);
    if ($stmt->execute()) {
        $prizes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    unset($stmt);
}
// ------------------------------

// --- NEW: SHIPMENT STATISTICS QUERIES ---
$stats = [
    'total' => 0,
    'pending' => 0,
    'in_transit' => 0,
    'delivered' => 0,
    'on_hold' => 0
];

// Helper to get count
function get_count($pdo, $status = null) {
    if ($status) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM shipments WHERE status = :status");
        $stmt->execute(['status' => $status]);
    } else {
        $stmt = $pdo->query("SELECT COUNT(*) FROM shipments");
    }
    return $stmt->fetchColumn();
}

$stats['total'] = get_count($pdo);
$stats['pending'] = get_count($pdo, 'Pending');
$stats['in_transit'] = get_count($pdo, 'In Transit');
$stats['delivered'] = get_count($pdo, 'Delivered');
$stats['on_hold'] = get_count($pdo, 'On Hold');
// ------------------------------------------
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <?php if ($use_favicon): ?>
    <link rel="icon" type="<?php echo $favicon_mime; ?>" href="../<?php echo $favicon_path; ?>">
    <?php endif; ?>
	<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="assets/css/style.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Dawning+of+a+New+Day&family=Epilogue:ital,wght@0,100..900;1,100..900&family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Mulish:ital,wght@0,200..1000;1,200..1000&family=Open+Sans:ital,wght@0,300..800;1,300..800&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Raleway:ital,wght@0,100..900;1,100..900&family=Red+Hat+Text:ital,wght@0,300..700;1,300..700&family=Roboto:ital,wght@0,100..900;1,100..900&family=Space+Mono:ital,wght@0,400;0,700;1,400;1,700&family=Work+Sans:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
    <style>
         .text-gold {color: var(--bs-gold) !important;}
         .card-enhanced {border: none;border-radius: 15px;box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);background-color: #fff;margin-bottom: 24px; transition: transform 0.2s; }
         .card-stats { padding: 1.5rem; position: relative; overflow: hidden; color: white; min-height: 140px; display: flex; flex-direction: column; justify-content: space-between; }
         .card-stats i { position: absolute; right: -10px; bottom: -10px; font-size: 5rem; opacity: 0.15; transform: rotate(-15deg); }
         .card-stats .label { font-size: 0.85rem; font-weight: 600; opacity: 0.9; text-transform: uppercase; letter-spacing: 0.5px; }
         .card-stats .value { font-size: 2.2rem; font-weight: 800; line-height: 1; }
         
         .bg-stat-total { background: linear-gradient(135deg, #1e3c72, #2a5298); }
         .bg-stat-pending { background: linear-gradient(135deg, #606c88, #3f4c6b); }
         .bg-stat-transit { background: linear-gradient(135deg, #00b4db, #0083b0); }
         .bg-stat-delivered { background: linear-gradient(135deg, #11998e, #38ef7d); }
         .bg-stat-hold { background: linear-gradient(135deg, #f2994a, #f2c94c); }
         
         .form-control, .form-control:focus {border-radius: 8px;border: 1px solid #ced4da;box-shadow: none;padding: 10px 15px;}
         .form-control:focus {border-color: var(--bs-crimson-light);box-shadow: 0 0 0 0.25rem var(--bs-crimson-faded);}
         .header-bg {background: var(--crimson-gradient);color: white;}
         .sidebar-link:hover, .sidebar-link.active {color: white;background: #3a3a3a;}
         .custom-file-upload {border: 2px dashed #ced4da;border-radius: 12px;padding: 20px;text-align: center;cursor: pointer;transition: all 0.3s;background: #fafafa;}
         .custom-file-upload:hover {border-color: var(--bs-crimson-light); background: #fff;}


    @media (max-width: 768px) {
        .card-stats { min-height: 120px; padding: 1rem; }
        .card-stats .value { font-size: 1.8rem; }
        .table-enhanced thead { display: none; }
        .table-responsive { overflow: visible !important; border: none !important; }
        .table-enhanced, .table-enhanced tbody { display: block !important; width: 100% !important; }
        .table-enhanced { background: transparent; border: none; box-shadow: none; margin: 0 !important; }
        .table-enhanced tbody { display: flex !important; flex-direction: column; gap: 15px; }
        .table-enhanced tr { display: flex !important; flex-direction: column; border: none; border-radius: 16px; background: #fff; padding: 20px; box-shadow: 0 10px 25px rgba(0,0,0,0.08); position: relative; overflow: hidden; width: 100%; }
        .table-enhanced tr::before { content: ""; position: absolute; left: 0; top: 0; width: 4px; height: 100%; background: var(--bs-crimson-light); }
        .table-enhanced td { display: flex !important; justify-content: space-between; align-items: center; border-bottom: 1px solid #f8f9fa; padding: 12px 0 !important; min-height: 50px; font-size: 0.95rem; width: 100% !important; color: #1e293b !important; }
        .table-enhanced td::before { content: attr(data-label); font-weight: 800; text-align: left; color: #64748b; font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px; flex: 0 0 100px; }
        .mobile-value-wrapper { flex: 1; display: flex; justify-content: flex-end; align-items: center; text-align: right; min-width: 0; overflow: hidden; }
        .table-enhanced td[data-label="Remove"] { border-bottom: none; justify-content: center !important; padding-top: 20px !important; }
        .table-enhanced td[data-label="Remove"]::before { display: none; }
        .table-enhanced .btn-danger { width: 100%; padding: 12px; border-radius: 10px; }
        .main-content-wrapper { padding: 20px 15px; }
    }
    </style>
</head>
<body>

     <?php include "nav.php" ?>
    
    <div id="wrapper">
        
        <?php include "header.php" ?>

        <div class="main-content-wrapper">
            <div id="main-content" class="container-fluid">
                <h4 class="fw-bolder mb-4">Admin Dashboard</h4>
                
                <?php if (isset($_SESSION['message'])): ?>
                    <div class="alert alert-<?php echo $_SESSION['message_type']; ?> alert-dismissible fade show mb-4 border-0 shadow-sm" role="alert">
                        <?php echo $_SESSION['message']; unset($_SESSION['message']); unset($_SESSION['message_type']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- --- STATS SECTION --- -->
                <div class="row g-4 mb-5">
                    <div class="col-xl-2 col-lg-4 col-md-6">
                        <div class="card-enhanced card-stats bg-stat-total">
                            <span class="label">Total Shipments</span>
                            <span class="value"><?php echo $stats['total']; ?></span>
                            <i class="bi bi-box-seam"></i>
                        </div>
                    </div>
                    <div class="col-xl-2 col-lg-4 col-md-6">
                        <div class="card-enhanced card-stats bg-stat-pending">
                            <span class="label">Pending</span>
                            <span class="value"><?php echo $stats['pending']; ?></span>
                            <i class="bi bi-clock-history"></i>
                        </div>
                    </div>
                    <div class="col-xl-2 col-lg-4 col-md-6">
                        <div class="card-enhanced card-stats bg-stat-transit">
                            <span class="label">In Transit</span>
                            <span class="value"><?php echo $stats['in_transit']; ?></span>
                            <i class="bi bi-truck"></i>
                        </div>
                    </div>
                    <div class="col-xl-3 col-lg-6 col-md-6">
                        <div class="card-enhanced card-stats bg-stat-delivered">
                            <span class="label">Successfully Delivered</span>
                            <span class="value"><?php echo $stats['delivered']; ?></span>
                            <i class="bi bi-check2-circle"></i>
                        </div>
                    </div>
                    <div class="col-xl-3 col-lg-6 col-md-6">
                        <div class="card-enhanced card-stats bg-stat-hold">
                            <span class="label">On Hold / Delayed</span>
                            <span class="value"><?php echo $stats['on_hold']; ?></span>
                            <i class="bi bi-exclamation-triangle"></i>
                        </div>
                    </div>
                </div>
                <!-- ---------------------- -->

                <div class="row g-4 mb-5">
                    <!-- Left: Add Testimonial -->
                    <div class="col-lg-5">
                        <div class="card-enhanced p-4 border-0">
                            <h6 class="fw-bold mb-4 border-bottom pb-2">
                                <i class="bi bi-patch-plus me-2"></i> Add Platform Review
                            </h6>
                            
                            <form action="process_prize.php" method="post" enctype="multipart/form-data">
                                <div class="row g-3">
                                    <div class="col-12">
                                        <label for="winner_name" class="form-label">Full Name</label>
                                        <input type="text" name="winner_name" id="winner_name" class="form-control" placeholder="e.g., Sarah L." required>
                                    </div>
                                    <div class="col-12">
                                        <label for="winner_location" class="form-label">Location</label>
                                        <input type="text" name="winner_location" id="winner_location" class="form-control" placeholder="e.g., Sydney, Australia" required>
                                    </div>
                                    <div class="col-12">
                                        <label for="prize_won" class="form-label">Service Used</label>
                                        <input type="text" name="prize_won" id="prize_won" class="form-control" placeholder="e.g., Express Air Freight" required>
                                    </div>
                                    <div class="col-12">
                                        <label for="testimonial" class="form-label">Review Quote</label>
                                        <textarea name="testimonial" id="testimonial" class="form-control" rows="3" placeholder="Enter review..." required></textarea>
                                    </div>
                                    <div class="col-12">
                                        <div class="custom-file-upload" onclick="document.getElementById('winner_image').click();" id="upload-area">
                                            <i class="bi bi-image file-upload-icon d-block mb-1"></i>
                                            <small class="text-muted" id="file-name-preview">Upload User Avatar (JPG/PNG)</small>
                                            <input type="file" name="winner_image" id="winner_image" accept="image/jpeg, image/png" hidden required>
                                        </div>
                                    </div>
                                    <div class="col-12 text-center">
                                        <button type="submit" class="btn btn-crimson w-100 fw-bold py-2 mt-2">
                                            PUBLISH REVIEW
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Right: Reviews List -->
                    <div class="col-lg-7">
                        <div class="card-enhanced p-4 border-0 h-100">
                            <h6 class="fw-bold mb-4 border-bottom pb-2">
                                <i class="bi bi-stars me-2"></i> Latest Customer Reviews
                            </h6>
                            <?php if (!empty($prizes)): ?>
                            <!-- Desktop Table View -->
                            <div class="d-none d-md-block">
                                <div class="table-responsive">
                                    <table class="table-enhanced table-borderless table-hover align-middle">
                                        <thead class="bg-light">
                                            <tr class="text-muted small text-uppercase">
                                                <th>User</th>
                                                <th>Service</th>
                                                <th class="text-end">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($prizes as $prize): ?>
                                            <tr style="border-bottom: 1px solid #f8f9fa;">
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <?php if (!empty($prize['winner_image_path'])): ?>
                                                            <img src="<?php echo htmlspecialchars($prize['winner_image_path']); ?>" alt="" class="rounded-circle me-3" style="width: 40px; height: 40px; object-fit: cover; border: 2px solid #f8f9fa;">
                                                        <?php else: ?>
                                                            <div class="rounded-circle me-3 bg-light d-flex align-items-center justify-content-center" style="width: 40px; height: 40px; border: 2px solid #f8f9fa;">
                                                                <i class="bi bi-person text-muted"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                        <div>
                                                            <div class="fw-bold"><?php echo htmlspecialchars($prize['winner_name']); ?></div>
                                                            <div class="text-muted small"><?php echo htmlspecialchars($prize['winner_location']); ?></div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td class="small"><?php echo htmlspecialchars($prize['prize_won']); ?></td>
                                                <td class="text-end">
                                                    <div class="d-flex justify-content-end gap-2">
                                                        <a href="edit_review.php?id=<?php echo $prize['id']; ?>" class="btn btn-sm btn-outline-primary" title="Edit Review">
                                                            <i class="bi bi-pencil-square"></i>
                                                        </a>
                                                        <a href="process_prize.php?delete=<?php echo $prize['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this review?');" title="Delete Review">
                                                            <i class="bi bi-trash"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <!-- Mobile Premium Card View -->
                            <div class="d-md-none">
                                <div class="row g-3">
                                    <?php foreach ($prizes as $prize): ?>
                                    <div class="col-12">
                                        <div class="card border-0 shadow-sm rounded-4 overflow-hidden" style="background: #ffffff; border-left: 4px solid var(--bs-crimson-light) !important;">
                                            <div class="card-body p-3">
                                                <div class="d-flex align-items-center mb-3">
                                                    <?php if (!empty($prize['winner_image_path'])): ?>
                                                        <img src="<?php echo htmlspecialchars($prize['winner_image_path']); ?>" alt="" class="rounded-circle me-3 shadow-sm" style="width: 50px; height: 50px; object-fit: cover; border: 2px solid #f8f9fa;">
                                                    <?php else: ?>
                                                        <div class="rounded-circle me-3 bg-light d-flex align-items-center justify-content-center shadow-sm" style="width: 50px; height: 50px; border: 2px solid #f8f9fa;">
                                                            <i class="bi bi-person text-muted fs-4"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                    <div class="flex-grow-1">
                                                        <h6 class="fw-bold mb-0 text-dark"><?php echo htmlspecialchars($prize['winner_name']); ?></h6>
                                                        <small class="text-muted"><i class="bi bi-geo-alt me-1"></i><?php echo htmlspecialchars($prize['winner_location']); ?></small>
                                                    </div>
                                                </div>
                                                <div class="bg-light rounded-3 p-3 mb-3 border-start border-3 border-secondary border-opacity-10">
                                                    <small class="text-muted d-block text-uppercase fw-bold mb-1" style="font-size: 0.65rem; letter-spacing: 1px;">Service Used</small>
                                                    <div class="fw-semibold text-secondary small"><?php echo htmlspecialchars($prize['prize_won']); ?></div>
                                                </div>
                                                <div class="row g-2 pt-1">
                                                    <div class="col-6">
                                                        <a href="edit_review.php?id=<?php echo $prize['id']; ?>" class="btn btn-outline-primary btn-sm w-100 rounded-pill py-2 fw-bold">
                                                            <i class="bi bi-pencil-square me-2"></i> EDIT
                                                        </a>
                                                    </div>
                                                    <div class="col-6">
                                                        <a href="process_prize.php?delete=<?php echo $prize['id']; ?>" class="btn btn-outline-danger btn-sm w-100 rounded-pill py-2 fw-bold" onclick="return confirm('Delete this review?');">
                                                            <i class="bi bi-trash3 me-2"></i> DELETE
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <!-- Pagination -->
                            <?php if ($total_review_pages > 1): ?>
                            <div class="mt-4">
                                <nav aria-label="Review pagination">
                                    <ul class="pagination pagination-sm justify-content-center mb-0">
                                        <li class="page-item <?php echo ($review_page <= 1) ? 'disabled' : ''; ?>">
                                            <a class="page-link" href="?rpage=<?php echo $review_page - 1; ?>#main-content" tabindex="-1">Prev</a>
                                        </li>
                                        <?php for ($i = 1; $i <= $total_review_pages; $i++): ?>
                                        <li class="page-item <?php echo ($review_page == $i) ? 'active' : ''; ?>">
                                            <a class="page-link" href="?rpage=<?php echo $i; ?>#main-content"><?php echo $i; ?></a>
                                        </li>
                                        <?php endfor; ?>
                                        <li class="page-item <?php echo ($review_page >= $total_review_pages) ? 'disabled' : ''; ?>">
                                            <a class="page-link" href="?rpage=<?php echo $review_page + 1; ?>#main-content">Next</a>
                                        </li>
                                    </ul>
                                </nav>
                            </div>
                            <?php endif; ?>

                            <?php else: ?>
                                <div class="text-center py-5 text-muted">
                                    <i class="bi bi-chat-left-dots" style="font-size: 3rem; opacity: 0.3;"></i>
                                    <p class="mt-2">No reviews published yet.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

            </div>
        </div>
        </div>

   <?php include "footer.php" ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const fileInput = document.getElementById('winner_image');
        const fileNameDisplay = document.getElementById('file-name-preview');
        const uploadArea = document.getElementById('upload-area');
        const defaultText = 'JPG, PNG, or GIF file (Max 2MB)';

        // 1. File Selection Listener
        fileInput.addEventListener('change', function() {
            if (this.files && this.files.length > 0) {
                fileNameDisplay.textContent = this.files[0].name;
                uploadArea.style.borderColor = 'var(--bs-gold)';
            } else {
                fileNameDisplay.textContent = defaultText;
                uploadArea.style.borderColor = '#ced4da';
            }
        });

        // 2. Drag-and-Drop Listeners (Enhanced UX)
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, preventDefaults, false);
        });
        function preventDefaults (e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, () => {
                uploadArea.classList.add('bg-light');
                uploadArea.style.borderColor = 'var(--bs-crimson-light)';
            }, false);
        });
        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, () => {
                uploadArea.classList.remove('bg-light');
                if (!fileInput.files || fileInput.files.length === 0) {
                    uploadArea.style.borderColor = '#ced4da';
                }
            }, false);
        });

        uploadArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            let dt = e.dataTransfer;
            let files = dt.files;
            
            fileInput.files = files; 
            fileInput.dispatchEvent(new Event('change'));
        }
    });
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>