<?php
/**
 * Admin — Reviews / Testimonials Manager
 * Path: admin/reviews.php
 */
require_once 'layout-header.php';

$msg_success = '';
$msg_error   = '';
$action      = isset($_GET['action']) ? $_GET['action'] : 'list';
$edit_id     = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$conn) {
    echo "<main class='flex-1 p-6'><div class='p-4 bg-red-950/40 border border-red-800 text-red-200 text-sm rounded-xl'>ডাটাবেজ কানেক্টেড নেই!</div></main>";
    require_once 'layout-footer.php';
    exit;
}

$prefix = DB_PREFIX;

if ($action === 'delete' && $edit_id > 0) {
    $stmt = $conn->prepare("DELETE FROM `{$prefix}testimonials` WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute() ? $msg_success = 'রিভিউ মুছে ফেলা হয়েছে।' : $msg_error = $conn->error;
    $stmt->close();
    $action = 'list';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action'])) {
    $client_name = trim($_POST['client_name'] ?? '');
    $rating      = intval($_POST['rating'] ?? 5);
    $review_text = trim($_POST['review_text'] ?? '');
    $source      = trim($_POST['source'] ?? 'Website');
    $review_id   = intval($_POST['review_id'] ?? 0);
    $rating      = max(1, min(5, $rating));

    if (empty($client_name) || empty($review_text)) {
        $msg_error = 'নাম ও রিভিউ টেক্সট বাধ্যতামূলক।';
    } else {
        if ($_POST['form_action'] === 'edit_review' && $review_id > 0) {
            $stmt = $conn->prepare("UPDATE `{$prefix}testimonials` SET client_name=?, rating=?, review_text=?, source=? WHERE id=?");
            $stmt->bind_param("sissi", $client_name, $rating, $review_text, $source, $review_id);
        } else {
            $date = date('Y-m-d');
            $stmt = $conn->prepare("INSERT INTO `{$prefix}testimonials` (client_name, rating, review_text, source, review_date) VALUES (?,?,?,?,?)");
            $stmt->bind_param("sisss", $client_name, $rating, $review_text, $source, $date);
        }
        $stmt->execute() ? $msg_success = 'রিভিউ সফলভাবে সেভ হয়েছে!' : $msg_error = $conn->error;
        $stmt->close();
        $action = 'list';
    }
}
?>

<main class="flex-1 p-6 md:p-8 space-y-6">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-slate-800/80 pb-5">
        <div>
            <h1 class="text-2xl font-black text-white uppercase tracking-wider">Reviews Manager</h1>
            <p class="text-xs text-slate-400 mt-1">ক্লায়েন্ট রিভিউ ও টেস্টিমোনিয়াল ম্যানেজ করুন</p>
        </div>
        <?php if ($action === 'list'): ?>
        <a href="?action=add" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-plus-circle mr-2"></i> Add Review
        </a>
        <?php else: ?>
        <a href="reviews.php" class="bg-slate-800 text-slate-300 px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-arrow-left mr-2"></i> Back
        </a>
        <?php endif; ?>
    </div>

    <?php if ($msg_success): ?>
    <div class="p-4 bg-emerald-950/40 border border-emerald-800 text-emerald-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-circle-check mr-3"></i> <?php echo $msg_success; ?>
    </div>
    <?php endif; ?>
    <?php if ($msg_error): ?>
    <div class="p-4 bg-red-950/40 border border-red-800 text-red-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-triangle-exclamation mr-3"></i> <?php echo $msg_error; ?>
    </div>
    <?php endif; ?>

    <?php if ($action === 'add' || $action === 'edit'):
        $form_action = 'add_review';
        $val = ['client_name'=>'','rating'=>5,'review_text'=>'','source'=>'Website'];
        if ($action === 'edit' && $edit_id > 0) {
            $form_action = 'edit_review';
            $stmt = $conn->prepare("SELECT * FROM `{$prefix}testimonials` WHERE id = ?");
            $stmt->bind_param("i", $edit_id);
            $stmt->execute();
            if ($row = $stmt->get_result()->fetch_assoc()) $val = $row;
            $stmt->close();
        }
    ?>
    <form method="post" action="" class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 space-y-5 max-w-2xl">
        <input type="hidden" name="form_action" value="<?php echo $form_action; ?>">
        <?php if ($action === 'edit'): ?><input type="hidden" name="review_id" value="<?php echo $edit_id; ?>"><?php endif; ?>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Client Name *</label>
            <input type="text" name="client_name" value="<?php echo htmlspecialchars($val['client_name']); ?>" required
                placeholder="Tanvir Ahmed (Facility Manager)"
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Rating (1-5) *</label>
            <div class="flex gap-2" id="rating-stars">
                <?php for ($i = 1; $i <= 5; $i++): ?>
                <button type="button" onclick="setRating(<?php echo $i; ?>)" data-star="<?php echo $i; ?>"
                    class="star-btn text-2xl transition-colors <?php echo $i <= $val['rating'] ? 'text-amber-400' : 'text-slate-600'; ?>">
                    <i class="fa-solid fa-star"></i>
                </button>
                <?php endfor; ?>
            </div>
            <input type="hidden" name="rating" id="rating-input" value="<?php echo (int)$val['rating']; ?>">
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Review Text *</label>
            <textarea name="review_text" rows="4" required
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100"><?php echo htmlspecialchars($val['review_text']); ?></textarea>
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Source</label>
            <select name="source" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
                <?php foreach (['Website','Google','Facebook','LinkedIn','Other'] as $src): ?>
                <option value="<?php echo $src; ?>" <?php echo ($val['source'] === $src) ? 'selected' : ''; ?>><?php echo $src; ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <button type="submit" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-8 py-3.5 rounded-xl text-xs uppercase">
            <i class="fa-solid fa-floppy-disk mr-2"></i> Save Review
        </button>
    </form>

    <script>
        function setRating(n) {
            document.getElementById('rating-input').value = n;
            document.querySelectorAll('.star-btn').forEach(btn => {
                btn.classList.toggle('text-amber-400', parseInt(btn.dataset.star) <= n);
                btn.classList.toggle('text-slate-600', parseInt(btn.dataset.star) > n);
            });
        }
    </script>

    <?php else:
        $result = $conn->query("SELECT * FROM `{$prefix}testimonials` ORDER BY id DESC");
    ?>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <?php if ($result && $result->num_rows > 0):
            while ($row = $result->fetch_assoc()): ?>
        <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-5 hover:border-amber-500/20 transition-all group">
            <div class="flex items-start justify-between gap-3 mb-3">
                <div>
                    <h3 class="font-bold text-white text-sm"><?php echo htmlspecialchars($row['client_name']); ?></h3>
                    <div class="flex text-amber-400 text-xs mt-1">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                        <i class="fa-solid fa-star<?php echo $i > $row['rating'] ? ' opacity-20' : ''; ?>"></i>
                        <?php endfor; ?>
                    </div>
                </div>
                <div class="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <a href="?action=edit&id=<?php echo $row['id']; ?>" class="p-1.5 bg-slate-800 hover:bg-sky-500 text-sky-400 hover:text-slate-950 rounded-lg text-xs"><i class="fa-solid fa-pen"></i></a>
                    <a href="?action=delete&id=<?php echo $row['id']; ?>" onclick="return confirm('মুছে ফেলবেন?');" class="p-1.5 bg-slate-800 hover:bg-red-500 text-red-400 hover:text-white rounded-lg text-xs"><i class="fa-solid fa-trash"></i></a>
                </div>
            </div>
            <p class="text-xs text-slate-400 leading-relaxed italic">"<?php echo htmlspecialchars($row['review_text']); ?>"</p>
            <div class="flex items-center justify-between mt-3 pt-3 border-t border-slate-800/80">
                <span class="text-[10px] font-bold uppercase text-slate-500 bg-slate-800 px-2 py-0.5 rounded"><?php echo htmlspecialchars($row['source']); ?></span>
                <span class="text-[10px] text-slate-600"><?php echo htmlspecialchars($row['review_date'] ?? ''); ?></span>
            </div>
        </div>
        <?php endwhile; else: ?>
        <div class="col-span-full text-center py-16 text-slate-500">
            <i class="fa-solid fa-star text-3xl mb-3 block opacity-30"></i>
            <p class="text-sm">কোনো রিভিউ নেই। Add Review ক্লিক করুন।</p>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

</main>

<?php require_once 'layout-footer.php'; ?>
