<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '/home12/fiberule/public_html/kartikthanaweddingdinner/config/db.php';

$message = "";

// Capture redirect messages
if (isset($_GET['msg'])) {
    $message = htmlspecialchars($_GET['msg']);
}

// --- UPDATED BULK DELETE HANDLER ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_delete'])) {
    $ids = $_POST['delete_ids'] ?? [];
    $type = $_POST['bulk_type'] ?? '';
    
    if (!empty($ids) && in_array($type, ['rsvp', 'wish'])) {
        try {
            $table = ($type === 'rsvp') ? 'rsvps' : 'wishes';
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $stmt = $pdo->prepare("DELETE FROM $table WHERE id IN ($placeholders)");
            $stmt->execute(array_map('intval', $ids));
            
            // Redirect to refresh the list and show updated counts
            header("Location: " . $_SERVER['PHP_SELF'] . "?msg=" . count($ids) . "+items+removed+successfully");
            exit;
        } catch (PDOException $e) {
            $message = "Error: " . $e->getMessage();
        }
    } else {
        $message = "No items selected. Please tick a box first.";
    }
}

// 1. HANDLE SINGLE DELETION
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id']) && isset($_GET['type'])) {
    $id = (int)$_GET['id'];
    $type = $_GET['type'];
    
    try {
        $table = ($type === 'rsvp') ? 'rsvps' : 'wishes';
        $stmt = $pdo->prepare("DELETE FROM $table WHERE id = ?");
        $stmt->execute([$id]);
        
        header("Location: " . $_SERVER['PHP_SELF'] . "?msg=Deleted+successfully");
        exit;
    } catch (PDOException $e) {
        $message = "Error deleting: " . $e->getMessage();
    }
}

// 2. HANDLE MANUAL ADDITION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['manual_add'])) {
    $name = $_POST['name'] ?? '';
    $pax = $_POST['pax'] ?? 1;
    $status = "Manual"; 

    if (!empty($name)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO rsvps (name, status, pax, created_at) VALUES (?, ?, ?, NOW())");
            $stmt->execute([$name, $status, (int)$pax]);
            header("Location: " . $_SERVER['PHP_SELF'] . "?msg=Guest+Added");
            exit;
        } catch (PDOException $e) {
            die("Database Error: " . $e->getMessage());
        }
    }
}

// 3. FETCH DATA
$rsvps = $pdo->query("SELECT * FROM rsvps ORDER BY created_at DESC")->fetchAll();
$wishes = $pdo->query("SELECT * FROM wishes ORDER BY created_at DESC")->fetchAll();

// 4. TOTALS
$totalPax = array_sum(array_column($rsvps, 'pax')); 
$totalRsvps = count($rsvps);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Guest Management | Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
    :root {
        --primary: #0b1b33;
        --accent: #d4af37;
        --bg: #f8f9fa;
        --white: #ffffff;
        --text: #333;
        --success: #2e7d32;
    }
    body { margin:0; font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: var(--bg); color: var(--text); line-height: 1.6; }
    .header { background: var(--primary); color: var(--white); padding: 30px 40px; display: flex; justify-content: space-between; align-items: center; border-bottom: 4px solid var(--accent); }
    .header h1 { margin:0; font-weight: 300; letter-spacing: 2px; font-size: 24px; text-transform: uppercase; }
    .container { padding: 40px; max-width: 1200px; margin: 0 auto; }
    .alert { background: #e8f5e9; color: #2e7d32; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #c8e6c9; }
    .stats-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 40px; }
    .stat-card { background: var(--white); padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); text-align: center; border-bottom: 3px solid var(--accent); transition: transform 0.3s ease; }
    .stat-card:hover { transform: translateY(-5px); }
    .stat-card h4 { margin: 0 0 10px 0; color: #888; text-transform: uppercase; font-size: 12px; letter-spacing: 1px; }
    .stat-card .count { font-size: 36px; font-weight: bold; color: var(--primary); }
    .card { background: var(--white); border-radius: 15px; padding: 30px; margin-bottom: 30px; box-shadow: 0 10px 30px rgba(0,0,0,0.04); border: 1px solid #eaeaea; }
    .card h3 { margin-top:0; color: var(--primary); font-weight: 600; font-size: 20px; border-left: 4px solid var(--accent); padding-left: 15px; margin-bottom: 25px; }
    .manual-form { display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap; background: #fdfdfd; padding: 20px; border-radius: 10px; border: 1px solid #eee; }
    .form-group { display: flex; flex-direction: column; }
    .form-group label { font-size: 13px; font-weight: 600; margin-bottom: 8px; color: var(--primary); }
    input[type="text"], input[type="number"] { padding: 12px; border: 1px solid #ddd; border-radius: 8px; transition: border 0.3s; font-size: 15px; }
    input:focus { outline: none; border-color: var(--accent); }
    .btn-add { background: var(--primary); color: white; border: none; padding: 12px 25px; border-radius: 8px; cursor: pointer; font-weight: bold; transition: 0.3s; }
    .btn-add:hover { background: #152a4a; box-shadow: 0 4px 10px rgba(11,27,51,0.2); }
    .table-responsive { overflow-x: auto; }
    table { width:100%; border-collapse: collapse; }
    th { text-align: left; padding: 18px; border-bottom: 2px solid #eee; color: #999; font-weight: 600; font-size: 13px; text-transform: uppercase; }
    td { padding: 18px; border-bottom: 1px solid #f1f1f1; font-size: 15px; }
    tr:hover { background: #fafafa; }
    .badge { padding: 5px 12px; border-radius: 20px; font-size: 12px; font-weight: bold; text-transform: uppercase; }
    .badge-online { background: #e8f5e9; color: var(--success); }
    .badge-manual { background: #e3f2fd; color: #1976d2; }
    .pax-num { background: var(--primary); color: white; padding: 4px 10px; border-radius: 6px; font-weight: bold; }
    .delete-link { color: #ff5252; text-decoration: none; font-size: 13px; font-weight: 600; padding: 8px 15px; border-radius: 6px; border: 1px solid #ff5252; transition: 0.3s; }
    .delete-link:hover { background: #ff5252; color: white; }
    .wish-text { font-style: italic; color: #555; background: #fff9e6; padding: 10px; border-radius: 8px; border-left: 3px solid var(--accent); }
    .btn-bulk-delete { background: #ff5252; color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: bold; margin-bottom: 15px; }
</style>
</head>
<body>

<div class="header">
    <h1>Wedding Guest Concierge</h1>
    <div>Welcome, Admin</div>
</div>

<div class="container">

    <?php if ($message): ?>
        <div class="alert"><?= $message ?></div>
    <?php endif; ?>

    <div class="stats-container">
        <div class="stat-card">
            <h4>Total Confirmed Seats</h4>
            <div class="count"><?= $totalPax ?></div>
        </div>
        <div class="stat-card">
            <h4>Guest Groups</h4>
            <div class="count"><?= $totalRsvps ?></div>
        </div>
        <div class="stat-card">
            <h4>Wishes Received</h4>
            <div class="count"><?= count($wishes) ?></div>
        </div>
    </div>

    <div class="card">
        <h3>Add Individual Guest</h3>
        <form method="POST" class="manual-form">
            <div class="form-group">
                <label>Guest Full Name</label>
                <input type="text" name="name" required placeholder="e.g. John Doe">
            </div>
            <div class="form-group">
                <label>Seats (Pax)</label>
                <input type="number" name="pax" value="1" min="1" style="width: 80px;">
            </div>
            <input type="hidden" name="manual_add" value="1">
            <button type="submit" class="btn-add">Confirm Guest</button>
        </form>
    </div>

    <div class="card">
        <h3>RSVP Guest Registry</h3>
        <form method="POST" onsubmit="return confirm('Delete selected guests?');">
            <input type="hidden" name="bulk_type" value="rsvp">
            <button type="submit" name="bulk_delete" class="btn-bulk-delete">Delete Selected Guests</button>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th style="width: 40px;"></th>
                            <th>Guest Name</th>
                            <th>Source</th>
                            <th>Pax</th>
                            <th>Added On</th>
                            <th style="text-align: right;">Management</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($rsvps as $r): ?>
                        <tr>
                            <td><input type="checkbox" name="delete_ids[]" value="<?= $r['id'] ?>"></td>
                            <td><strong><?= htmlspecialchars($r['name']) ?></strong></td>
                            <td>
                                <span class="badge <?= ($r['status'] == 'Manual' ? 'badge-manual' : 'badge-online') ?>">
                                    <?= ($r['status'] == 'Manual' ? 'Manual Entry' : 'Online RSVP') ?>
                                </span>
                            </td>
                            <td><span class="pax-num"><?= $r['pax'] ?></span></td>
                            <td style="color: #999; font-size: 13px;"><?= date('M d, Y', strtotime($r['created_at'])) ?></td>
                            <td style="text-align: right;">
                                <a class="delete-link" href="?action=delete&type=rsvp&id=<?= $r['id'] ?>"
                                onclick="return confirm('Remove this guest?')">Remove</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </form>
    </div>

    <div class="card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="margin: 0;">Guest Wishes & Messages</h3>
            <a href="export_wishes.php" class="btn-add" style="text-decoration: none; background: #2e7d32;">📥 Download Excel</a>
        </div>
        <form method="POST" onsubmit="return confirm('Delete selected wishes?');">
            <input type="hidden" name="bulk_type" value="wish">
            <button type="submit" name="bulk_delete" class="btn-bulk-delete">Delete Selected Wishes</button>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th style="width: 40px;"></th>
                            <th>Guest</th>
                            <th>Source</th>
                            <th>Message</th>
                            <th style="text-align: right;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($wishes as $w): ?>
                        <tr>
                            <td><input type="checkbox" name="delete_ids[]" value="<?= $w['id'] ?>"></td>
                            <td style="width: 200px;"><strong><?= htmlspecialchars($w['name']) ?></strong></td>
                            <td>
                                <span class="badge <?= (isset($w['source']) && $w['source'] == 'QR Scan' ? 'badge-manual' : 'badge-online') ?>">
                                    <?= htmlspecialchars($w['source'] ?? 'Invitation') ?>
                                </span>
                            </td>
                            <td><div class="wish-text">"<?= htmlspecialchars($w['message']) ?>"</div></td>
                            <td style="text-align: right;">
                                <a class="delete-link" href="?action=delete&type=wish&id=<?= $w['id'] ?>"
                                onclick="return confirm('Delete this wish?')">Delete</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </form>
    </div>

</div>
</body>
</html>