<?php
require_once '../config.php';

$conn = get_db_connection();
$message = '';
$message_type = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add' || $_POST['action'] === 'edit') {
            $author_name = trim($_POST['author_name'] ?? '');
            $author_role = trim($_POST['author_role'] ?? 'Verified Customer');
            $content = trim($_POST['content'] ?? '');
            $rating = intval($_POST['rating'] ?? 5);
            $display_order = intval($_POST['display_order'] ?? 0);

            if (empty($author_name) || empty($content)) {
                $message = 'Author Name and Content are required!';
                $message_type = 'danger';
            } else {
                if ($_POST['action'] === 'add') {
                    $stmt = $conn->prepare("INSERT INTO reviews (author_name, author_role, content, rating, display_order) VALUES (?, ?, ?, ?, ?)");
                    $stmt->bind_param("sssii", $author_name, $author_role, $content, $rating, $display_order);
                    if ($stmt->execute()) {
                        $message = 'Review added successfully!';
                        $message_type = 'success';
                    } else {
                        $message = 'Error adding review: ' . $stmt->error;
                        $message_type = 'danger';
                    }
                    $stmt->close();
                } else {
                    $id = intval($_POST['id']);
                    $stmt = $conn->prepare("UPDATE reviews SET author_name = ?, author_role = ?, content = ?, rating = ?, display_order = ? WHERE id = ?");
                    $stmt->bind_param("sssiii", $author_name, $author_role, $content, $rating, $display_order, $id);
                    if ($stmt->execute()) {
                        $message = 'Review updated successfully!';
                        $message_type = 'success';
                    } else {
                        $message = 'Error updating review: ' . $stmt->error;
                        $message_type = 'danger';
                    }
                    $stmt->close();
                }
            }
        } elseif ($_POST['action'] === 'delete') {
            $id = intval($_POST['id']);
            $stmt = $conn->prepare("DELETE FROM reviews WHERE id = ?");
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                $message = 'Review deleted successfully!';
                $message_type = 'success';
            } else {
                $message = 'Error deleting review: ' . $stmt->error;
                $message_type = 'danger';
            }
            $stmt->close();
        }
    }
}

// Get all reviews
$reviews_result = $conn->query("SELECT * FROM reviews ORDER BY display_order ASC, created_at DESC");
$reviews = [];
if ($reviews_result) {
    while ($row = $reviews_result->fetch_assoc()) {
        $reviews[] = $row;
    }
}

// Get review for editing
$edit_review = null;
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM reviews WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $row = $result->fetch_assoc()) {
        $edit_review = $row;
    }
    $stmt->close();
}

$page_title = 'Review Management';
require_once 'includes/admin-header.php';
?>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title"><?php echo $edit_review ? 'Edit Review' : 'Add New Review'; ?></h2>
        <?php if ($edit_review): ?>
            <a href="reviews" class="btn btn-secondary btn-sm">Cancel</a>
        <?php endif; ?>
    </div>

    <form method="POST" action="">
        <input type="hidden" name="action" value="<?php echo $edit_review ? 'edit' : 'add'; ?>">
        <?php if ($edit_review): ?>
            <input type="hidden" name="id" value="<?php echo $edit_review['id']; ?>">
        <?php endif; ?>

        <div class="form-row">
            <div class="form-group">
                <label for="author_name">Author Name *</label>
                <input type="text" id="author_name" name="author_name" class="form-control" required
                    value="<?php echo htmlspecialchars($edit_review['author_name'] ?? ''); ?>"
                    placeholder="e.g. Rafael W.">
            </div>

            <div class="form-group">
                <label for="author_role">Author Role</label>
                <input type="text" id="author_role" name="author_role" class="form-control"
                    value="<?php echo htmlspecialchars($edit_review['author_role'] ?? 'Verified Customer'); ?>"
                    placeholder="e.g. Verified Customer">
            </div>
        </div>

        <div class="form-group">
            <label for="content">Review Content *</label>
            <textarea id="content" name="content" class="form-control" required style="min-height: 120px;"
                placeholder="Enter the review text..."><?php echo htmlspecialchars($edit_review['content'] ?? ''); ?></textarea>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label for="rating">Rating (Stars)</label>
                <select id="rating" name="rating" class="form-control">
                    <?php for ($i = 5; $i >= 1; $i--): ?>
                        <option value="<?php echo $i; ?>" <?php echo (isset($edit_review['rating']) && $edit_review['rating'] == $i) || (!isset($edit_review['rating']) && $i == 5) ? 'selected' : ''; ?>>
                            <?php echo $i; ?> Stars
                        </option>
                    <?php endfor; ?>
                </select>
            </div>

            <div class="form-group">
                <label for="display_order">Display Order</label>
                <input type="number" id="display_order" name="display_order" class="form-control"
                    value="<?php echo $edit_review['display_order'] ?? 0; ?>" min="0" placeholder="0">
            </div>
        </div>

        <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> <?php echo $edit_review ? 'Update Review' : 'Add Review'; ?>
        </button>
    </form>
</div>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">All Reviews (<?php echo count($reviews); ?>)</h2>
    </div>

    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>Author</th>
                    <th>Rating</th>
                    <th>Content</th>
                    <th>Order</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($reviews)): ?>
                    <tr>
                        <td colspan="5" style="text-align: center; padding: 40px; color: var(--text-muted);">No reviews
                            found. Add your first review above.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($reviews as $review): ?>
                        <tr>
                            <td>
                                <div style="font-weight: 700;"><?php echo htmlspecialchars($review['author_name']); ?></div>
                                <div style="font-size: 12px; color: var(--text-muted);">
                                    <?php echo htmlspecialchars($review['author_role']); ?>
                                </div>
                            </td>
                            <td>
                                <div style="color: #f59e0b;">
                                    <?php for ($i = 0; $i < $review['rating']; $i++): ?>
                                        <i class="fas fa-star"></i>
                                    <?php endfor; ?>
                                </div>
                            </td>
                            <td>
                                <div style="max-width: 400px; font-style: italic; color: var(--text-muted);">
                                    "<?php echo htmlspecialchars(substr($review['content'], 0, 100)) . (strlen($review['content']) > 100 ? '...' : ''); ?>"
                                </div>
                            </td>
                            <td><?php echo $review['display_order']; ?></td>
                            <td>
                                <div style="display: flex; gap: 8px;">
                                    <a href="?edit=<?php echo $review['id']; ?>" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <form method="POST" action="" style="display: inline;"
                                        onsubmit="return confirm('Are you sure you want to delete this review?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $review['id']; ?>">
                                        <button type="submit" class="btn btn-danger btn-sm">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once 'includes/admin-footer.php'; ?>