<?php
$page_title = 'Edit Review - Admin';

if (!Admin::isLoggedIn()) {
    Utils::redirect('/routex/admin/login');
}

$review_model = new Review($pdo);
$review_id = $_GET['id'] ?? null;
$error = '';
$success = '';

if (!$review_id) {
    Utils::redirect('/routex/admin/reviews');
}

$review = $review_model->getById($review_id);
if (!$review) {
    Utils::redirect('/routex/admin/reviews');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update') {
        $data = [
            'reviewer_name' => $_POST['reviewer_name'] ?? '',
            'reviewer_email' => $_POST['reviewer_email'] ?? '',
            'rating' => intval($_POST['rating'] ?? 5),
            'review_text' => $_POST['review_text'] ?? '',
            'is_featured' => isset($_POST['is_featured']) ? 1 : 0
        ];

        if (empty($data['reviewer_name']) || empty($data['review_text'])) {
            $error = 'Name and review text are required.';
        } elseif ($data['rating'] < 1 || $data['rating'] > 5) {
            $error = 'Rating must be between 1 and 5.';
        } else {
            // Handle image upload
            if (!empty($_FILES['image']['name'])) {
                // Delete old image if exists
                if ($review['image_path']) {
                    $old_filename = basename($review['image_path']);
                    Utils::deleteFile($old_filename);
                }

                $upload = Utils::uploadFile($_FILES['image']);
                if ($upload['success']) {
                    $data['image_path'] = $upload['path'];
                } else {
                    $error = $upload['error'];
                }
            }

            if (!$error) {
                if ($review_model->update($review_id, $data)) {
                    $success = 'Review updated successfully!';
                    $review = $review_model->getById($review_id);
                } else {
                    $error = 'Failed to update review.';
                }
            }
        }
    } elseif ($action === 'delete') {
        // Delete image if exists
        if ($review['image_path']) {
            $filename = basename($review['image_path']);
            Utils::deleteFile($filename);
        }

        if ($review_model->delete($review_id)) {
            Utils::redirect('/routex/admin/reviews');
        } else {
            $error = 'Failed to delete review.';
        }
    }
}

$csrf_token = Utils::generateCSRFToken();
require_once __DIR__ . '/../../includes/trackheader.php';
?>

<section class="min-h-screen bg-gray-50">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <!-- Header -->
        <div class="flex justify-between items-center mb-8">
            <div>
                <h1 class="text-4xl font-bold text-gray-900">Edit Review</h1>
                <p class="text-gray-600 mt-2">By <?php echo htmlspecialchars($review['reviewer_name']); ?></p>
            </div>
            <a href="/routex/admin/reviews" class="btn-secondary">
                <i class="fas fa-arrow-left mr-2"></i>Back
            </a>
        </div>

        <!-- Form -->
        <div class="bg-white rounded-xl shadow-md p-8">
            <?php if ($error): ?>
            <div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg mb-6">
                <p class="text-red-700"><?php echo htmlspecialchars($error); ?></p>
            </div>
            <?php endif; ?>

            <?php if ($success): ?>
            <div class="bg-green-50 border-l-4 border-green-500 p-4 rounded-lg mb-6">
                <p class="text-green-700"><?php echo htmlspecialchars($success); ?></p>
            </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data" class="space-y-6">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">

                <div>
                    <label class="block text-gray-900 font-semibold mb-2">Reviewer Name *</label>
                    <input type="text" name="reviewer_name" value="<?php echo htmlspecialchars($review['reviewer_name']); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600" required>
                </div>

                <div>
                    <label class="block text-gray-900 font-semibold mb-2">Email</label>
                    <input type="email" name="reviewer_email" value="<?php echo htmlspecialchars($review['reviewer_email'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                </div>

                <div>
                    <label class="block text-gray-900 font-semibold mb-2">Rating *</label>
                    <div class="flex space-x-2">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                        <label class="flex items-center cursor-pointer">
                            <input type="radio" name="rating" value="<?php echo $i; ?>" <?php echo $i === $review['rating'] ? 'checked' : ''; ?> class="mr-2">
                            <i class="fas fa-star text-yellow-400"></i>
                        </label>
                        <?php endfor; ?>
                    </div>
                </div>

                <div>
                    <label class="block text-gray-900 font-semibold mb-2">Review Text *</label>
                    <textarea name="review_text" rows="6" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600" required><?php echo htmlspecialchars($review['review_text']); ?></textarea>
                </div>

                <div>
                    <label class="block text-gray-900 font-semibold mb-2">Reviewer Image</label>
                    <?php if ($review['image_path']): ?>
                    <div class="mb-4">
                        <img src="<?php echo htmlspecialchars($review['image_path']); ?>" alt="<?php echo htmlspecialchars($review['reviewer_name']); ?>" class="w-24 h-24 rounded-lg object-cover">
                    </div>
                    <?php endif; ?>
                    <input type="file" name="image" accept="image/*" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                    <p class="text-gray-600 text-sm mt-2">Max 5MB. Formats: JPG, PNG, GIF</p>
                </div>

                <div>
                    <label class="flex items-center">
                        <input type="checkbox" name="is_featured" <?php echo $review['is_featured'] ? 'checked' : ''; ?> class="w-4 h-4 text-purple-600 rounded">
                        <span class="ml-2 text-gray-900 font-semibold">Featured on Homepage</span>
                    </label>
                </div>

                <!-- Buttons -->
                <div class="flex gap-4">
                    <button type="submit" class="btn-primary">
                        <i class="fas fa-save mr-2"></i>Save Changes
                    </button>
                    <a href="/routex/admin/reviews" class="btn-secondary">
                        <i class="fas fa-times mr-2"></i>Cancel
                    </a>
                </div>
            </form>

            <!-- Delete Button -->
            <form method="POST" onsubmit="return confirm('Are you sure you want to delete this review?');" class="mt-8 pt-8 border-t">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                <button type="submit" class="px-4 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition font-semibold">
                    <i class="fas fa-trash mr-2"></i>Delete Review
                </button>
            </form>
        </div>
    </div>
</section>

<footer class="bg-white border-t mt-20 no-print">
  <div class="max-w-7xl mx-auto px-4 py-6 text-center text-sm text-slate-500">
    © 2026 RoutexShipping. All rights reserved.
  </div>
</footer>
