<?php
require_once __DIR__ . '/config.php';
require_admin_login();

// --- POST ACTIONS ---
if (is_post()) {
    verify_csrf();

    // 1. Add subcategory
    if (isset($_POST['add_subcategory'])) {
        $service_id = (int)($_POST['service_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $order_text = trim($_POST['order_text'] ?? '');
        $status = (int)($_POST['status'] ?? 1);
        $notice = trim($_POST['notice'] ?? ''); 
        
        if (!$service_id || $name === '') {
            set_flash("Please provide all required data.", "danger");
        } else {
            $stmt = $pdo->prepare("INSERT INTO subcategories (service_id, name, price, order_text, status, notice) VALUES (?,?,?,?,?,?)");
            $stmt->execute([$service_id, $name, $price, $order_text, $status, $notice]);
            set_flash("Subcategory added successfully.", "success");
            redirect('subcategories.php');
        }
    }

    // 2. Update subcategory
    if (isset($_POST['update_subcategory'])) {
        $scid = (int)($_POST['scid'] ?? 0);
        $service_id = (int)($_POST['service_id'] ?? 0);
        $price = (float)($_POST['price'] ?? 0);
        $order_text = trim($_POST['order_text'] ?? '');
        $status = (int)($_POST['status'] ?? 1);
        $notice = trim($_POST['notice'] ?? '');

        if ($scid && $service_id) {
            $stmt = $pdo->prepare("UPDATE subcategories SET service_id=?, price=?, order_text=?, status=?, notice=? WHERE id=?");
            $stmt->execute([$service_id, $price, $order_text, $status, $notice, $scid]);
            set_flash("Subcategory updated successfully.", "success");
            redirect('subcategories.php');
        }
    }

    // 3. Individual Manual Status Toggle
    if (isset($_POST['toggle_status'])) {
        $scid = (int)($_POST['scid'] ?? 0);
        if ($scid) {
            $stmt = $pdo->prepare("UPDATE subcategories SET status = NOT status WHERE id = ?");
            $stmt->execute([$scid]);
            set_flash("Service status updated successfully.", "success");
            redirect('subcategories.php');
        }
    }

    // 4. Delete subcategory
    if (isset($_POST['delete_subcategory'])) {
        $scid = (int)($_POST['scid'] ?? 0);
        if ($scid) {
            $stmt = $pdo->prepare("DELETE FROM subcategories WHERE id=?");
            $stmt->execute([$scid]);
            set_flash("Subcategory deleted successfully.", "success");
            redirect('subcategories.php');
        }
    }

    // 5. Bulk Status Update
    if (isset($_POST['bulk_status_update'])) {
        try {
            $target_status = (int)$_POST['target_status']; 
            $stmt = $pdo->prepare("UPDATE subcategories SET status = ?");
            $stmt->execute([$target_status]);
            
            $msg = ($target_status === 0) ? "All services are now DISABLED." : "All services are now ENABLED.";
            set_flash($msg, "success");
        } catch (PDOException $e) {
            set_flash("Database Error: Status column check required.", "danger");
        }
        redirect('subcategories.php');
    }
}

// --- FETCH DATA ---
$search = trim($_GET['search'] ?? '');
try {
    if ($search !== '') {
        $query = "SELECT sc.*, s.name AS service_name FROM subcategories sc JOIN services s ON s.id = sc.service_id WHERE sc.name LIKE ? OR s.name LIKE ? ORDER BY sc.id DESC";
        $stmt = $pdo->prepare($query);
        $stmt->execute(["%$search%", "%$search%"]);
        $sub_all = $stmt->fetchAll();
    } else {
        $sub_all = $pdo->query("SELECT sc.*, s.name AS service_name FROM subcategories sc JOIN services s ON s.id=sc.service_id ORDER BY sc.id DESC")->fetchAll();
    }
} catch (Exception $e) {
    $sub_all = [];
}

$services_list = $pdo->query("SELECT * FROM services ORDER BY name ASC")->fetchAll();

function paginate($items, $perPage = 12) {
    $total = count($items);
    $pages = max(1, ceil($total / $perPage));
    $current = max(1, (int)($_GET['page'] ?? 1));
    $start = ($current - 1) * $perPage;
    return [array_slice($items, $start, $perPage), $pages, $current];
}

list($subcats, $pages, $current) = paginate($sub_all, 12);

function render_pagination($pages, $current, $search = '') {
    if ($pages < 2) return '';
    $search_param = !empty($search) ? "&search=" . urlencode($search) : "";
    $html = '<nav><ul class="pagination pagination-sm justify-content-center">';
    for ($i = 1; $i <= $pages; $i++) {
        $active = $i == $current ? 'active' : '';
        $html .= "<li class='page-item $active'><a class='page-link border-0 shadow-sm mx-1' href='?page=$i$search_param'>$i</a></li>";
    }
    $html .= '</ul></nav>';
    return $html;
}

require_once 'header.php';
?>

<style>
    :root {
        --brand-color: #230133;
        --brand-hover: #3b0354;
    }
    .text-brand { color: var(--brand-color) !important; }
    .btn-primary, .btn-success { background-color: var(--brand-color) !important; border-color: var(--brand-color) !important; color: #fff !important; }
    .btn-primary:hover, .btn-success:hover { background-color: var(--brand-hover) !important; }
    .card-header { background-color: var(--brand-color) !important; color: #fff !important; }
    .page-item.active .page-link { background-color: var(--brand-color) !important; color: #fff !important; }
    .page-link { color: var(--brand-color); }
    .border-brand { border-color: var(--brand-color) !important; }
    .form-control:focus, .form-select:focus { border-color: var(--brand-color); box-shadow: 0 0 0 0.2rem rgba(35, 1, 51, 0.25); }
    .table-brand-header thead { background-color: #f8f9fa; border-top: 3px solid var(--brand-color); }
</style>

<div class="container-fluid py-3">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <h1 class="h3 text-brand fw-bold mb-0">Subcategory Management</h1>
        <form action="" method="GET" class="d-flex" style="min-width: 300px;">
            <input type="text" name="search" class="form-control me-2 border-brand" placeholder="Search by name..." value="<?php echo h($search); ?>">
            <button type="submit" class="btn btn-primary"><i class="bi bi-search"></i></button>
        </form>
    </div>

    <?php show_flash(); ?>

    <div class="card bg-white border-brand shadow-sm mb-4" style="border-left: 5px solid var(--brand-color);">
        <div class="card-body d-flex justify-content-between align-items-center py-2 flex-wrap">
            <span class="fw-bold text-brand small text-uppercase">Bulk Status Actions:</span>
            <div class="mt-2 mt-md-0">
                <form method="post" class="d-inline" onsubmit="return confirm('Disable all services?');">
                    <?php csrf_field(); ?>
                    <input type="hidden" name="target_status" value="0">
                    <button type="submit" name="bulk_status_update" class="btn btn-sm btn-outline-danger fw-bold me-2">
                        <i class="bi bi-x-circle"></i> Disable All
                    </button>
                </form>
                <form method="post" class="d-inline" onsubmit="return confirm('Enable all services?');">
                    <?php csrf_field(); ?>
                    <input type="hidden" name="target_status" value="1">
                    <button type="submit" name="bulk_status_update" class="btn btn-sm btn-success fw-bold">
                        <i class="bi bi-check-circle"></i> Enable All
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="card shadow-sm mb-4 border-0">
        <div class="card-header py-3 rounded-top">
            <h6 class="m-0 fw-bold"><i class="bi bi-plus-circle me-2"></i>Add New Subcategory</h6>
        </div>
        <div class="card-body border">
            <form method="post" class="row g-3">
                <?php csrf_field(); ?>
                <div class="col-md-3">
                    <label class="form-label fw-bold small">Service Category</label>
                    <select name="service_id" class="form-select border-brand" required>
                        <option value="" disabled selected>Select Service...</option>
                        <?php foreach ($services_list as $sv): ?>
                            <option value="<?php echo $sv['id']; ?>"><?php echo h($sv['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-bold small">Package Name</label>
                    <input type="text" name="name" class="form-control" placeholder="e.g. 100 Diamonds" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label fw-bold small">Price (৳)</label>
                    <input type="number" step="0.01" name="price" class="form-control" placeholder="0.00" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label fw-bold small">Order Label</label>
                    <input type="text" name="order_text" class="form-control" placeholder="e.g. Player ID">
                </div>
                <div class="col-md-2">
                    <label class="form-label fw-bold small">Initial Status</label>
                    <select name="status" class="form-select">
                        <option value="1">Active</option>
                        <option value="0">Inactive</option>
                    </select>
                </div>
                <div class="col-md-12">
                    <label class="form-label fw-bold small">Service Notice (Shown on Order Page)</label>
                    <textarea name="notice" class="form-control" rows="2" placeholder="Example: Processing time 5-30 mins..."></textarea>
                </div>
                <div class="col-12 text-end">
                    <button type="submit" class="btn btn-success px-5 fw-bold" name="add_subcategory">Save Subcategory</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="card-header py-3 rounded-top">
            <h6 class="m-0 fw-bold">Active Subcategories List</h6>
        </div>
        <div class="card-body border">
            <div class="table-responsive">
                <table class="table table-hover table-brand-header align-middle">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Parent Service</th>
                            <th>Subcategory</th>
                            <th>Price</th>
                            <th>Notice</th>
                            <th>Status</th>
                            <th class="text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($subcats)): ?>
                            <tr><td colspan="7" class="text-center py-4 text-muted">No records found.</td></tr>
                        <?php else: foreach ($subcats as $sc): ?>
                            <tr>
                                <td class="text-muted small">#<?php echo $sc['id']; ?></td>
                                <td class="fw-bold"><?php echo h($sc['service_name']); ?></td>
                                <td><?php echo h($sc['name']); ?></td>
                                <td class="text-brand fw-bold">৳ <?php echo number_format($sc['price'], 2); ?></td>
                                <td>
                                    <?php if(!empty($sc['notice'])): ?>
                                        <span class="badge rounded-pill bg-light text-brand border border-brand" title="<?php echo h($sc['notice']); ?>" style="cursor: help;">
                                            <i class="bi bi-info-circle me-1"></i> Has Notice
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted small">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if(isset($sc['status']) && $sc['status'] == 1): ?>
                                        <span class="badge bg-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">Disabled</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <form method="post" class="d-inline">
                                        <?php csrf_field(); ?>
                                        <input type="hidden" name="scid" value="<?php echo $sc['id']; ?>">
                                        <button type="submit" name="toggle_status" class="btn btn-sm <?php echo $sc['status'] == 1 ? 'btn-outline-danger' : 'btn-outline-success'; ?>" title="Switch Status">
                                            <i class="bi <?php echo $sc['status'] == 1 ? 'bi-power' : 'bi-play-fill'; ?>"></i>
                                        </button>
                                    </form>

                                    <button type="button" class="btn btn-sm btn-primary ms-1" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $sc['id']; ?>">
                                        <i class="bi bi-pencil-square"></i>
                                    </button>

                                    <form method="post" class="d-inline ms-1">
                                        <?php csrf_field(); ?>
                                        <input type="hidden" name="scid" value="<?php echo $sc['id']; ?>">
                                        <button type="submit" name="delete_subcategory" class="btn btn-sm btn-danger" onclick="return confirm('Delete this subcategory permanently?')">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            
                            <div class="modal fade" id="editModal<?php echo $sc['id']; ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form method="post">
                                            <?php csrf_field(); ?>
                                            <input type="hidden" name="scid" value="<?php echo $sc['id']; ?>">
                                            <div class="modal-header bg-brand text-white">
                                                <h5 class="modal-title">Edit Package: <?php echo h($sc['name']); ?></h5>
                                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <div class="mb-3">
                                                    <label class="form-label fw-bold small">Parent Service</label>
                                                    <select name="service_id" class="form-select border-brand" required>
                                                        <?php foreach ($services_list as $sv): ?>
                                                            <option value="<?php echo $sv['id']; ?>" <?php echo ($sv['id'] == $sc['service_id']) ? 'selected' : ''; ?>>
                                                                <?php echo h($sv['name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="mb-3">
                                                    <label class="form-label fw-bold small">Price (৳)</label>
                                                    <input type="number" step="0.01" class="form-control border-brand" name="price" value="<?php echo $sc['price']; ?>" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label class="form-label fw-bold small">Order Placeholder Text</label>
                                                    <input type="text" class="form-control border-brand" name="order_text" value="<?php echo h($sc['order_text']); ?>">
                                                </div>
                                                <div class="mb-3">
                                                    <label class="form-label fw-bold small">Status</label>
                                                    <select name="status" class="form-select border-brand">
                                                        <option value="1" <?php echo ($sc['status'] == 1) ? 'selected' : ''; ?>>Active</option>
                                                        <option value="0" <?php echo ($sc['status'] == 0) ? 'selected' : ''; ?>>Inactive</option>
                                                    </select>
                                                </div>
                                                <div class="mb-3">
                                                    <label class="form-label fw-bold small">Service Notice</label>
                                                    <textarea name="notice" class="form-control border-brand" rows="3"><?php echo h($sc['notice']); ?></textarea>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                                                <button type="submit" name="update_subcategory" class="btn btn-primary fw-bold">Update Package</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>

                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="mt-4"><?php echo render_pagination($pages, $current, $search); ?></div>
        </div>
    </div>
</div>

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