<?php
session_start();
require 'function.php';
require 'config.php';

if (!is_subscription_active($_SESSION['id'])) {
    header('location:profile.php?info=expired');
    exit;
}
$user_id = $_SESSION['id'];
$active_event_id = get_active_event_id();

if (!$active_event_id) {
    echo "<script>alert('Please select an active event first.'); window.location.href='manage-events.php';</script>";
    exit;
}

// --- UPDATE LOGIC ---
if(isset($_POST['update_event_general'])) {
    $acara = mysqli_real_escape_string($koneksi, $_POST['acara']);
    $jam = mysqli_real_escape_string($koneksi, $_POST['jam']);
    $tanggal = mysqli_real_escape_string($koneksi, $_POST['tanggal']);
    $timezone_event = mysqli_real_escape_string($koneksi, $_POST['timezone']);
    $link_undangan = mysqli_real_escape_string($koneksi, $_POST['link_undangan'] ?? '');
    
    // Auto-migrate column
    $check_col = mysqli_query($koneksi, "SHOW COLUMNS FROM `event_id` LIKE 'link_undangan'");
    if(mysqli_num_rows($check_col) == 0) {
        mysqli_query($koneksi, "ALTER TABLE `event_id` ADD `link_undangan` VARCHAR(255) NULL AFTER `acara`");
    }
    
    mysqli_query($koneksi,"UPDATE `event_id` SET acara='$acara', jam='$jam', tanggal='$tanggal', timezone='$timezone_event', link_undangan='$link_undangan' WHERE id = '$active_event_id'");
    header("Location: event?info=valid"); exit;
}

if(isset($_POST['update_event_display'])) {
    $cover = isset($_POST['cover']) ? 1 : 0;
    $bg = isset($_POST['bg']) ? 1 : 0;
    $font = mysqli_real_escape_string($koneksi, $_POST['font']);
    $color = mysqli_real_escape_string($koneksi, $_POST['color']);
    $font_color = mysqli_real_escape_string($koneksi, $_POST['font_color']);
    $opacity = (float)$_POST['opacity'];
    $text = mysqli_real_escape_string($koneksi, $_POST['text']);
    $timer = (int)$_POST['timer'];
    $size_welcome = (int)$_POST['size_welcome'];
    $size_tamu = (int)$_POST['size_tamu'];
    
    // Auto-migrate if needed
    $check_fc = mysqli_query($koneksi, "SHOW COLUMNS FROM `event_id` LIKE 'font_color'");
    if(mysqli_num_rows($check_fc) == 0) mysqli_query($koneksi, "ALTER TABLE `event_id` ADD `font_color` VARCHAR(10) DEFAULT '#ffffff' AFTER `color`") or die(mysqli_error($koneksi));
    $check_op = mysqli_query($koneksi, "SHOW COLUMNS FROM `event_id` LIKE 'opacity'");
    if(mysqli_num_rows($check_op) == 0) mysqli_query($koneksi, "ALTER TABLE `event_id` ADD `opacity` DECIMAL(2,1) DEFAULT 0.8 AFTER `font_color`") or die(mysqli_error($koneksi));

    mysqli_query($koneksi,"UPDATE `event_id` SET cover='$cover', bg='$bg', font='$font', color='$color', font_color='$font_color', opacity='$opacity', text='$text', timer='$timer', size_welcome='$size_welcome', size_tamu='$size_tamu' WHERE id = '$active_event_id'");
    header("Location: event?info=valid"); exit;
}

if(isset($_POST['update_iframe'])) {
    $iframe = mysqli_real_escape_string($koneksi, $_POST['iframe']);
    mysqli_query($koneksi,"UPDATE `event_id` SET iframe='$iframe' WHERE id = '$active_event_id'");
    header("Location: event?info=valid"); exit;
}

if(isset($_POST['upload_event_image'])){
    $folder = "uploads/"; 
    $valid = array('jpg','png','jpeg'); 
    $nama_gambar = $_FILES['gambar']['name']; 
    if(strlen($nama_gambar)){   
        $ext = strtolower(pathinfo($nama_gambar, PATHINFO_EXTENSION));
        if(in_array($ext,$valid)){   
            $gambarnya = time()."_event_".$active_event_id.".".$ext;
            if(move_uploaded_file($_FILES['gambar']['tmp_name'], $folder.$gambarnya)){   
                mysqli_query($koneksi,"UPDATE event_id SET image='$folder$gambarnya' WHERE id='$active_event_id'");
                $_SESSION["sukses"] = 'Image uploaded successfully';
            }
        }
    }
    header("Location: event"); exit;
}

if(isset($_POST['addcat'])) {
    $category_name = mysqli_real_escape_string($koneksi, $_POST['category_name']);
    $res = mysqli_query($koneksi,"INSERT INTO categories(category_name, event_id) VALUES('$category_name', '$active_event_id')");
    if($res) {
        header("Location: event?info=valid"); exit;
    } else {
        $_SESSION['error_db'] = mysqli_error($koneksi);
        header("Location: event?info=error"); exit;
    }
}

if(isset($_POST['update_event_wa'])) {
    $pesan = mysqli_real_escape_string($koneksi, $_POST['pesan']);
    
    $check_col2 = mysqli_query($koneksi, "SHOW COLUMNS FROM `event_id` LIKE 'text_wa'");
    if(mysqli_num_rows($check_col2) == 0) mysqli_query($koneksi, "ALTER TABLE `event_id` ADD `text_wa` TEXT NULL AFTER `link_undangan`");
    
    mysqli_query($koneksi,"UPDATE `event_id` SET text_wa='$pesan' WHERE id = '$active_event_id'");
    header("Location: event?info=valid"); exit;
}

// --- FETCH DATA ---
$event_data = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM event_id WHERE id = '$active_event_id'"));
$admin_data = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT whatsapp FROM users_id WHERE role = 'admin' LIMIT 1"));
$fallback_text = "Terima kasih banyak atas kehadiran Bapak/Ibu/Saudara/i [nama] di Hari Bahagia Kami, pada hari [tgl] jam [jam].\nTerima kasih atas doa restu terbaik yang Anda berikan kepada Kami dan Keluarga.";
$default_pesan = !empty($admin_data['whatsapp']) ? $admin_data['whatsapp'] : $fallback_text;
$shots = mysqli_query($koneksi, "SELECT * FROM categories WHERE event_id = '$active_event_id'");

require 'header.php';
?>

<div class="container py-4">
    <div class="row mb-4">
        <div class="col-md-12">
             <h3 class="fw-bold text-gradient d-inline-block">Event Settings: <?= $event_data['acara'] ?></h3>
             <p class="text-muted">Configure localized styling and information for this specific event.</p>
        </div>
    </div>

    <div class="row g-4">
        <!-- General Info -->
        <div class="col-lg-6">
            <div class="glass-card mb-4 h-100">
                <h5 class="fw-bold mb-4"><i class="bi bi-info-circle"></i> General Information</h5>
                <form action="" method="POST">
                    <div class="mb-3">
                        <label class="form-label">Event Name</label>
                        <input type="text" class="form-control" name="acara" value="<?= $event_data['acara'] ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Invitation Link</label>
                        <input type="url" class="form-control" name="link_undangan" value="<?= $event_data['link_undangan'] ?? '' ?>" placeholder="https://momenpedia.com/andiputri/?to=">
                        <div class="form-text small">Use this for the shortcode [link-undangan] in messages.</div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label">Date</label>
                            <input type="text" class="form-control datepicker" name="tanggal" value="<?= $event_data['tanggal'] ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Time</label>
                            <input type="text" class="form-control timepicker" name="jam" value="<?= $event_data['jam'] ?>" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Event Timezone</label>
                        <select name="timezone" class="form-control">
                            <?php $selection = array('Asia/Jakarta', 'Asia/Makassar','Asia/Jayapura'); ?>
                            <?php foreach ($selection as $sel) {
                                $selected = ($event_data['timezone'] == $sel) ? "selected" : "";
                                echo '<option '.$selected.' value="'.$sel.'">'.$sel.'</option>';
                            } ?>
                        </select>
                    </div>
                    <button class="btn btn-primary w-100" type="submit" name="update_event_general">Update General Info</button>
                </form>
            </div>
        </div>

        <!-- Display & Style -->
        <div class="col-lg-6">
            <div class="glass-card mb-4 h-100">
                <h5 class="fw-bold mb-4"><i class="bi bi-palette"></i> Style & Display</h5>
                <form action="" method="POST">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label">Font Family</label>
                            <select name="font" class="form-control">
                                <?php $fonts = array('Poppins', 'Raleway','Great Vibes','Nicconne','Merriweather');
                                foreach($fonts as $f) {
                                    $sel = ($event_data['font'] == $f) ? 'selected' : '';
                                    echo "<option $sel value='$f'>$f</option>";
                                } ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Overlay Color</label>
                            <input type="color" class="form-control form-control-color w-100" name="color" value="<?= $event_data['color'] ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Overlay Opacity</label>
                            <div class="d-flex align-items-center gap-2">
                                <input type="range" class="form-range" name="opacity" min="0" max="1" step="0.1" value="<?= $event_data['opacity'] ?? 0.8 ?>" oninput="this.nextElementSibling.value = this.value">
                                <output class="small fw-bold" style="min-width: 25px;"><?= $event_data['opacity'] ?? 0.8 ?></output>
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label">Font Color</label>
                            <input type="color" class="form-control form-control-color w-100" name="font_color" value="<?= $event_data['font_color'] ?? '#ffffff' ?>">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Welcome Text</label>
                        <input type="text" class="form-control" name="text" value="<?= $event_data['text'] ?>">
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label class="form-label small">Welcome Size</label>
                            <input type="number" class="form-control" name="size_welcome" value="<?= $event_data['size_welcome'] ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small">Name Size</label>
                            <input type="number" class="form-control" name="size_tamu" value="<?= $event_data['size_tamu'] ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small">Timer (ms)</label>
                            <input type="number" class="form-control" name="timer" value="<?= $event_data['timer'] ?>">
                        </div>
                    </div>
                    <div class="mb-4 d-flex flex-column gap-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="cover" value="1" id="c1" <?= $event_data['cover'] ? 'checked' : '' ?>>
                            <label class="form-check-label fw-semibold" for="c1">Show Name Event on Cover</label>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="bg" value="1" id="c2" <?= $event_data['bg'] ? 'checked' : '' ?>>
                            <label class="form-check-label fw-semibold" for="c2">Show Image BG on Cover</label>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="video_mode" value="1" id="c3" <?= !$event_data['bg'] ? 'checked' : '' ?> onclick="document.getElementById('c2').checked = !this.checked;">
                            <label class="form-check-label fw-semibold" for="c3">Show Video BG on Cover</label>
                        </div>
                    </div>
                    <button class="btn btn-primary w-100 py-2 shadow-sm" type="submit" name="update_event_display">Update Styles</button>
                </form>
            </div>
        </div>

        <!-- Background Image & Iframe -->
        <div class="col-lg-6">
            <div class="glass-card h-100">
                <h5 class="fw-bold mb-4"><i class="bi bi-image"></i> Media Settings</h5>
                <form action="" method="POST" enctype="multipart/form-data" class="mb-4">
                    <label class="form-label">Background Image</label>
                    <?php if($event_data['image']): ?>
                        <div class="mb-3">
                            <img src="<?= $event_data['image'] ?>" class="img-fluid rounded shadow-sm" style="max-height: 150px; border: 2px solid white;">
                        </div>
                    <?php endif; ?>
                    <div class="input-group">
                        <input type="file" class="form-control" name="gambar">
                        <button class="btn btn-primary" type="submit" name="upload_event_image">Upload</button>
                    </div>
                </form>
                <form action="" method="POST">
                    <label class="form-label">Background Video URL (YouTube)</label>
                    <div class="input-group">
                        <input type="text" class="form-control" name="iframe" value="<?= $event_data['iframe'] ?>" placeholder="https://www.youtube.com/watch?v=...">
                        <button class="btn btn-primary" type="submit" name="update_iframe">Update Video</button>
                    </div>
                    <div class="form-text small">Ensure the URL is a valid YouTube link.</div>
                </form>
            </div>
        </div>

        <!-- Categories -->
        <div class="col-lg-6">
            <div class="glass-card h-100">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold mb-0"><i class="bi bi-tags"></i> Categories</h5>
                    <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#AddCatModal"><i class="fa fa-plus"></i></button>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light"><tr><th>Name</th><th class="text-end">Action</th></tr></thead>
                        <tbody>
                            <?php 
                            if($shots) mysqli_data_seek($shots, 0); 
                            while($shots && $c = mysqli_fetch_assoc($shots)): ?>
                                <tr>
                                    <td class="fw-medium"><?= $c['category_name'] ?></td>
                                    <td class="text-end"><a href="hapus.php?id=<?= $c['id'] ?>" class="btn btn-outline-danger btn-sm px-2" onclick="return confirm('Delete this category?')"><i class="bi bi-trash"></i></a></td>
                                </tr>
                            <?php endwhile; ?>
                            <?php if(!$shots || mysqli_num_rows($shots) == 0): ?>
                                <tr><td colspan="2" class="text-center text-muted py-4">No categories added yet.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- WhatsApp Invitation Message -->
        <div class="col-lg-12">
            <div class="glass-card mb-4">
                <h5 class="fw-bold mb-3"><i class="bi bi-whatsapp"></i> Message Text</h5>
                <p class="small text-muted mb-4">Set the message when sending WhatsApp blasts for this event. Note: If left empty, it will fall back to your global profile message.</p>
                <form action="" method="POST">
                    <div class="mb-3">
                        <label class="form-label">Message Text</label>
                        <textarea class="form-control" name="pesan" rows="6" placeholder="<?= htmlspecialchars($default_pesan) ?>"><?= htmlspecialchars($event_data['text_wa'] ?? '') ?></textarea>
                        <div class="form-text small">Gunakan <code>[nama]</code> untuk Nama Tamu, <code>[tgl],[jam]</code> untuk tanggal dan waktu hadir, <code>[link-undangan]</code> untuk Link Undangan.</div>
                    </div>
                    <button class="btn btn-primary px-4" type="submit" name="update_event_wa">Update Event Message</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Category Modal - MOVED OUTSIDE FOR BETTER RELIABILITY -->
<div class="modal fade" id="AddCatModal" tabindex="-1" aria-labelledby="AddCatLabel" aria-hidden="true" style="z-index: 1070;">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content shadow-lg border-0">
            <div class="modal-header border-0 pb-0">
                <h6 class="fw-bold mb-0" id="AddCatLabel">New Category</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body pt-3">
                <form action="" method="post">
                    <div class="mb-3">
                        <input type="text" class="form-control" name="category_name" placeholder="Category Name" required autofocus>
                    </div>
                    <button type="submit" name="addcat" class="btn btn-primary w-100 py-2">Add Category</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function() {
        $(".datepicker").datepicker({ format: 'dd-mm-yyyy', autoclose: true, todayHighlight: true });
        $('.timepicker').datetimepicker({ format: 'HH:mm' });
        
        // Ensure BG switches are mutually exclusive visually
        $('#c2').on('change', function() {
            if($(this).is(':checked')) $('#c3').prop('checked', false);
        });
        $('#c3').on('change', function() {
            if($(this).is(':checked')) $('#c2').prop('checked', false);
        });
    });
</script>

<?php if(isset($_GET['info']) && $_GET['info'] == 'valid') echo '<script>swal("Success", "Operation completed successfully!", "success");</script>'; ?>
<?php if(isset($_GET['info']) && $_GET['info'] == 'error') { 
    $err = $_SESSION['error_db'] ?? 'Unknown database error';
    echo '<script>swal("Error", "'.addslashes($err).'", "error");</script>'; 
    unset($_SESSION['error_db']);
} ?>
<?php if(isset($_SESSION['sukses'])) { echo '<script>swal("Success", "'.$_SESSION['sukses'].'", "success");</script>'; unset($_SESSION['sukses']); } ?>

</body>
</html>