<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';

require_admin();

$pageTitle = 'Reviews';
$success = '';
$error = '';

if (isset($_GET['updated'])) {
    $success = 'Review updated successfully.';
}

if (isset($_GET['deleted'])) {
    $success = 'Review deleted successfully.';
}

if (isset($_GET['delete'])) {
    $deleteId = (int) $_GET['delete'];

    $stmt = $pdo->prepare("DELETE FROM review_media WHERE review_id = ?");
    $stmt->execute([$deleteId]);

    $stmt = $pdo->prepare("DELETE FROM reviews WHERE id = ?");
    $stmt->execute([$deleteId]);

    redirect(ADMIN_URL . '/reviews.php?deleted=1');
}

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $reviewId = (int) ($_POST['review_id'] ?? 0);
        $status = $_POST['status'] ?? 'pending';
        $verifiedPurchase = isset($_POST['verified_purchase']) ? 1 : 0;

        if ($reviewId <= 0) {
            $error = 'Invalid review.';
        } elseif (!in_array($status, ['pending', 'approved', 'rejected'], true)) {
            $error = 'Invalid review status.';
        } else {
            $stmt = $pdo->prepare("
                UPDATE reviews
                SET status = ?,
                    verified_purchase = ?
                WHERE id = ?
            ");

            $stmt->execute([
                $status,
                $verifiedPurchase,
                $reviewId
            ]);

            redirect(ADMIN_URL . '/reviews.php?updated=1');
        }
    }
}

$reviews = $pdo->query("
    SELECT r.*,
           p.product_name,
           p.slug AS product_slug,
           c.email AS customer_email,
           c.first_name,
           c.last_name
    FROM reviews r
    INNER JOIN products p ON r.product_id = p.id
    LEFT JOIN customers c ON r.customer_id = c.id
    ORDER BY r.id DESC
")->fetchAll();

$reviewMedia = [];

if ($reviews) {
    $reviewIds = array_column($reviews, 'id');
    $placeholders = implode(',', array_fill(0, count($reviewIds), '?'));

    $stmt = $pdo->prepare("
        SELECT *
        FROM review_media
        WHERE review_id IN ($placeholders)
        ORDER BY id ASC
    ");

    $stmt->execute($reviewIds);
    $mediaRows = $stmt->fetchAll();

    foreach ($mediaRows as $media) {
        $reviewMedia[$media['review_id']][] = $media;
    }
}

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Reviews</h1>
            <div class="admin-user">Approve, reject, verify, and manage customer product reviews.</div>
        </div>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-panel">
        <h2>All Reviews</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Customer</th>
                    <th>Rating</th>
                    <th>Review</th>
                    <th>Media</th>
                    <th>Status</th>
                    <th>Verified</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$reviews): ?>
                    <tr>
                        <td colspan="9">No reviews yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($reviews as $review): ?>
                    <tr>
                        <td>
                            <strong>
                                <a href="<?= e(BASE_URL); ?>/public/product.php?slug=<?= e($review['product_slug']); ?>" target="_blank">
                                    <?= e($review['product_name']); ?>
                                </a>
                            </strong>

                            <?php if (!empty($review['order_id'])): ?>
                                <br>
                                <small>Order ID: <?= e($review['order_id']); ?></small>
                            <?php endif; ?>
                        </td>

                        <td>
                            <?php if (!empty($review['customer_id'])): ?>
                                <?= e(trim(($review['first_name'] ?? '') . ' ' . ($review['last_name'] ?? '')) ?: 'Customer'); ?><br>
                                <small><?= e($review['customer_email'] ?? '-'); ?></small>
                            <?php else: ?>
                                Guest
                            <?php endif; ?>
                        </td>

                        <td>
                            <strong><?= e($review['rating']); ?>/5</strong><br>
                            <small>
                                <?php
                                $stars = '';
                                for ($i = 1; $i <= 5; $i++) {
                                    $stars .= $i <= (int)$review['rating'] ? '★' : '☆';
                                }
                                echo e($stars);
                                ?>
                            </small>
                        </td>

                        <td>
                            <?php if (!empty($review['review_title'])): ?>
                                <strong><?= e($review['review_title']); ?></strong><br>
                            <?php endif; ?>

                            <span><?= e(mb_strimwidth($review['review_text'] ?? '', 0, 160, '...')); ?></span>
                        </td>

                        <td>
                            <?php if (!empty($reviewMedia[$review['id']])): ?>
                                <?php foreach ($reviewMedia[$review['id']] as $media): ?>
                                    <a href="<?= e(BASE_URL . '/' . $media['media_path']); ?>" target="_blank">
                                        <?= e(ucfirst($media['media_type'])); ?>
                                    </a><br>
                                <?php endforeach; ?>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>

                        <td><?= e(ucfirst($review['status'])); ?></td>

                        <td><?= !empty($review['verified_purchase']) ? 'Yes' : 'No'; ?></td>

                        <td><?= e(date('d M Y', strtotime($review['created_at']))); ?></td>

                        <td>
                            <form method="POST" style="display:grid; gap:8px; min-width:180px;">
                                <?= csrf_field(); ?>

                                <input type="hidden" name="review_id" value="<?= e($review['id']); ?>">

                                <select name="status">
                                    <option value="pending" <?= $review['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="approved" <?= $review['status'] === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                    <option value="rejected" <?= $review['status'] === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                </select>

                                <label style="display:flex; align-items:center; gap:8px; font-size:13px;">
                                    <input type="checkbox" name="verified_purchase" <?= !empty($review['verified_purchase']) ? 'checked' : ''; ?>>
                                    Verified Purchase
                                </label>

                                <button type="submit" class="admin-btn">Update</button>

                                <a
                                    class="admin-btn admin-btn-light"
                                    href="<?= e(ADMIN_URL); ?>/reviews.php?delete=<?= e($review['id']); ?>"
                                    onclick="return confirm('Delete this review?');"
                                >
                                    Delete
                                </a>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>