<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_admin();

// Ensure schema
$pdo->exec("CREATE TABLE IF NOT EXISTS packages (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL UNIQUE,
  description TEXT,
  status TEXT NOT NULL DEFAULT 'active',
  discount_type TEXT NOT NULL DEFAULT 'none', -- none|percent|fixed|tiered
  discount_value REAL NOT NULL DEFAULT 0,
  discount_tiers_json TEXT,
  created_at TEXT NOT NULL
)");
$pdo->exec("CREATE TABLE IF NOT EXISTS package_items (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  package_id INTEGER NOT NULL,
  service_id INTEGER NOT NULL,
  quantity INTEGER NOT NULL DEFAULT 1,
  UNIQUE(package_id, service_id),
  FOREIGN KEY(package_id) REFERENCES packages(id) ON DELETE CASCADE,
  FOREIGN KEY(service_id) REFERENCES services(id) ON DELETE CASCADE
)");

function compute_package_total(PDO $pdo, int $package_id): array {
  $stmt = $pdo->prepare("
    SELECT SUM( (s.cac_fee + s.service_fee) * pi.quantity ) as base_total,
           p.discount_type, p.discount_value, p.discount_tiers_json
    FROM packages p
    LEFT JOIN package_items pi ON pi.package_id = p.id
    LEFT JOIN services s ON s.id = pi.service_id
    WHERE p.id=?
  ");
  $stmt->execute([$package_id]);
  $row = $stmt->fetch() ?: ['base_total'=>0,'discount_type'=>'none','discount_value'=>0,'discount_tiers_json'=>null];
  $base = (float)($row['base_total'] ?? 0);
  $discount = 0.0;
  $type = $row['discount_type'] ?? 'none';
  $val = (float)($row['discount_value'] ?? 0);
  if ($type === 'percent') $discount = $base * ($val/100);
  elseif ($type === 'fixed') $discount = $val;
  elseif ($type === 'tiered' && !empty($row['discount_tiers_json'])) {
    // tiers: [{threshold:number,percent?:number,fixed?:number}]
    $tiers = json_decode((string)$row['discount_tiers_json'], true);
    if (is_array($tiers)) {
      // threshold := number of items in package
      $q = (int)($pdo->query("SELECT COALESCE(SUM(quantity),0) q FROM package_items WHERE package_id=".$package_id)->fetch()['q'] ?? 0);
      usort($tiers, fn($a,$b)=>($a['threshold']??0)<=>($b['threshold']??0));
      foreach ($tiers as $t) {
        if ($q >= (int)($t['threshold'] ?? 0)) {
          if (isset($t['percent'])) $discount = max($discount, $base * ((float)$t['percent']/100));
          if (isset($t['fixed']))   $discount = max($discount, (float)$t['fixed']);
        }
      }
    }
  }
  $total = max(0, $base - $discount);
  return ['base'=>$base,'discount'=>$discount,'total'=>$total];
}

$action = $_POST['action'] ?? '';
if ($action === 'create') {
  ensure_csrf();
  $name = sanitize_str($_POST['name'] ?? '');
  $desc = sanitize_str($_POST['description'] ?? '');
  $dtype = in_array($_POST['discount_type'] ?? 'none', ['none','percent','fixed','tiered'], true) ? $_POST['discount_type'] : 'none';
  $dval = (float)($_POST['discount_value'] ?? 0);
  $tiers = trim((string)($_POST['discount_tiers_json'] ?? ''));
  $now = date('c');
  $stmt = $pdo->prepare("INSERT INTO packages (name,description,status,discount_type,discount_value,discount_tiers_json,created_at) VALUES (?,?,?,?,?,?,?)");
  $stmt->execute([$name,$desc,'active',$dtype,$dval,$tiers?:null,$now]);
  set_flash('success','Package created');
  redirect('/admin/packages.php');
}
if ($action === 'update') {
  ensure_csrf();
  $id = (int)($_POST['id'] ?? 0);
  $name = sanitize_str($_POST['name'] ?? '');
  $desc = sanitize_str($_POST['description'] ?? '');
  $dtype = in_array($_POST['discount_type'] ?? 'none', ['none','percent','fixed','tiered'], true) ? $_POST['discount_type'] : 'none';
  $dval = (float)($_POST['discount_value'] ?? 0);
  $tiers = trim((string)($_POST['discount_tiers_json'] ?? ''));
  $stmt = $pdo->prepare("UPDATE packages SET name=?, description=?, discount_type=?, discount_value=?, discount_tiers_json=? WHERE id=?");
  $stmt->execute([$name,$desc,$dtype,$dval,$tiers?:null,$id]);
  set_flash('success','Package updated');
  redirect('/admin/packages.php');
}
if ($action === 'toggle') {
  ensure_csrf();
  $id = (int)($_POST['id'] ?? 0);
  $pkg = $pdo->prepare("SELECT status FROM packages WHERE id=?"); $pkg->execute([$id]); $pkg = $pkg->fetch();
  if ($pkg) {
    $new = $pkg['status']==='active'?'inactive':'active';
    $pdo->prepare("UPDATE packages SET status=? WHERE id=?")->execute([$new,$id]);
    set_flash('success','Package status updated');
  }
  redirect('/admin/packages.php');
}
if ($action === 'delete') {
  ensure_csrf();
  $id = (int)($_POST['id'] ?? 0);
  $pdo->prepare("DELETE FROM packages WHERE id=?")->execute([$id]);
  set_flash('success','Package deleted');
  redirect('/admin/packages.php');
}
if ($action === 'items') {
  ensure_csrf();
  $id = (int)($_POST['id'] ?? 0);
  $services = $_POST['service_id'] ?? [];
  $qty = $_POST['quantity'] ?? [];
  // validation: only active services
  $valid = $pdo->query("SELECT id FROM services WHERE status='active'")->fetchAll();
  $validIds = array_flip(array_map(fn($r)=> (int)$r['id'], $valid));
  $pdo->prepare("DELETE FROM package_items WHERE package_id=?")->execute([$id]);
  $ins = $pdo->prepare("INSERT INTO package_items (package_id, service_id, quantity) VALUES (?,?,?)");
  foreach ($services as $sid) {
    $sid = (int)$sid;
    if (!isset($validIds[$sid])) continue;
    $q = max(1, (int)($qty[$sid] ?? 1));
    $ins->execute([$id,$sid,$q]);
  }
  set_flash('success','Package items updated');
  redirect('/admin/packages.php');
}

// Fetch data
$packages = $pdo->query("SELECT * FROM packages ORDER BY created_at DESC")->fetchAll();
$services = $pdo->query("SELECT id, service_name, (cac_fee+service_fee) AS total FROM services WHERE status='active' ORDER BY service_name ASC")->fetchAll();
include __DIR__ . '/../includes/header.php';
?>
<style>
/* Packages Page Styles */
.admin-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px; gap: 16px; flex-wrap: wrap; }
.admin-title { margin: 0; font-size: 28px; font-weight: 800; color: var(--text); letter-spacing: -0.5px; }
.admin-subtitle { margin: 4px 0 0; color: var(--muted); font-size: 15px; }

/* Package Cards */
.package-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 24px; margin-bottom: 32px; }
.pkg-card { background: #fff; border: 1px solid var(--border); border-radius: 24px; padding: 28px; display: flex; flex-direction: column; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); position: relative; overflow: hidden; }
.pkg-card:hover { border-color: var(--primary); transform: translateY(-4px); box-shadow: 0 20px 25px -5px rgba(0,0,0,0.05), 0 10px 10px -5px rgba(0,0,0,0.04); }

.pkg-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 16px; }
.pkg-name { font-size: 20px; font-weight: 800; color: var(--text); margin: 0; letter-spacing: -0.3px; }
.pkg-status { font-size: 11px; font-weight: 700; text-transform: uppercase; padding: 4px 12px; border-radius: 99px; letter-spacing: 0.5px; }
.status-active { background: #f0fdf4; color: #16a34a; border: 1px solid #bbf7d0; }
.status-inactive { background: #f1f5f9; color: #64748b; border: 1px solid #e2e8f0; }

.pkg-desc { font-size: 14px; color: var(--muted); line-height: 1.6; margin-bottom: 24px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; height: 44px; }

.pkg-pricing { background: #f8fafc; border-radius: 16px; padding: 20px; margin-bottom: 24px; border: 1px solid #f1f5f9; }
.pricing-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.pricing-row:last-child { margin-bottom: 0; padding-top: 12px; border-top: 1px solid #e2e8f0; }
.price-label { font-size: 12px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px; }
.price-value { font-size: 15px; font-weight: 700; color: var(--text); }
.price-total { font-size: 22px; font-weight: 800; color: var(--primary); }

.pkg-discount-tag { display: inline-flex; align-items: center; gap: 6px; background: #fff; border: 1px solid #e2e8f0; padding: 4px 10px; border-radius: 8px; font-size: 12px; font-weight: 700; color: #6366f1; margin-bottom: 20px; }

.pkg-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: auto; }

/* Modals */
dialog { border: none; border-radius: 28px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); max-width: 540px; width: 95%; padding: 0; overflow: hidden; }
dialog::backdrop { background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(8px); }
.modal-header { padding: 24px 32px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: #f8fafc; }
.modal-body { padding: 32px; max-height: 80vh; overflow-y: auto; }

.form-group { margin-bottom: 20px; }
.form-label { display: block; font-size: 14px; font-weight: 600; color: var(--text); margin-bottom: 8px; }
.form-input, .form-textarea, .form-select { width: 100%; padding: 12px 16px; border: 1px solid var(--border); border-radius: 12px; font-size: 15px; transition: all 0.2s; background: #fff; }
.form-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1); }

/* Item Selector */
.item-selector { background: #f8fafc; border-radius: 16px; padding: 16px; border: 1px solid #e2e8f0; max-height: 300px; overflow-y: auto; }
.item-row { display: flex; align-items: center; gap: 12px; padding: 10px; border-radius: 10px; transition: 0.2s; }
.item-row:hover { background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }

@media(max-width:767px){
  .admin-header { flex-direction: column; align-items: flex-start; }
  .package-grid { grid-template-columns: 1fr; }
}
</style>

<div class="admin-header">
    <div>
        <h1 class="admin-title">Package Management</h1>
        <p class="admin-subtitle">Bundle services with discounts to increase conversion.</p>
    </div>
    <button id="open-pkg" class="btn primary" style="padding:12px 24px; font-weight:700">
        <?=ui_icon('new', 18)?> Create New Package
    </button>
</div>

<!-- Add/Edit Package Dialog -->
<dialog id="pkg-dialog">
    <div class="modal-header">
        <h3 style="margin:0; font-size:20px; font-weight:800" id="modal-title">New Package</h3>
        <button class="close-dialog" style="background:none; border:none; font-size:28px; cursor:pointer; color:var(--muted)">&times;</button>
    </div>
    <div class="modal-body">
        <form method="post" id="pkg-form">
            <?=csrf_field()?>
            <input type="hidden" name="action" id="form-action" value="create">
            <input type="hidden" name="id" id="pkg-id" value="">
            
            <div class="form-group">
                <label class="form-label">Package Name</label>
                <input type="text" name="name" id="pkg-name" class="form-input" placeholder="e.g. Premium Business Bundle" required>
            </div>
            
            <div class="form-group">
                <label class="form-label">Description</label>
                <textarea name="description" id="pkg-desc" class="form-textarea" rows="3" placeholder="Explain what makes this package great..."></textarea>
            </div>
            
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:16px">
                <div class="form-group">
                    <label class="form-label">Discount Type</label>
                    <select name="discount_type" id="pkg-dtype" class="form-select">
                        <option value="none">No Discount</option>
                        <option value="percent">Percentage (%)</option>
                        <option value="fixed">Fixed Amount (₦)</option>
                        <option value="tiered">Tiered (Advanced)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Discount Value</label>
                    <input type="number" step="0.01" name="discount_value" id="pkg-dval" class="form-input" value="0">
                </div>
            </div>
            
            <div class="form-group" id="tiers-group" style="display:none">
                <label class="form-label">Tiered JSON Configuration</label>
                <input type="text" name="discount_tiers_json" id="pkg-tiers" class="form-input" placeholder='[{"threshold":3,"percent":5}]'>
                <p style="font-size:11px; color:var(--muted); margin-top:4px">Define discounts based on the number of items in the package.</p>
            </div>
            
            <div style="margin-top:32px; display:flex; gap:12px">
                <button type="button" class="btn btn-outline" style="flex:1" onclick="document.getElementById('pkg-dialog').close()">Cancel</button>
                <button class="btn primary" type="submit" style="flex:2; font-weight:700" id="submit-btn">Create Package</button>
            </div>
        </form>
    </div>
</dialog>

<!-- Package Items Dialog -->
<dialog id="items-dialog">
    <div class="modal-header">
        <h3 style="margin:0; font-size:20px; font-weight:800">Manage Items</h3>
        <button class="close-dialog" style="background:none; border:none; font-size:28px; cursor:pointer; color:var(--muted)">&times;</button>
    </div>
    <div class="modal-body">
        <form method="post" id="items-form">
            <?=csrf_field()?>
            <input type="hidden" name="action" value="items">
            <input type="hidden" name="id" id="items-pkg-id" value="">
            
            <p style="margin-top:0; font-size:14px; color:var(--muted); margin-bottom:20px">Select the services included in this bundle and their quantities.</p>
            
            <div class="item-selector">
                <?php foreach ($services as $s): $sid=(int)$s['id']; ?>
                    <div class="item-row">
                        <input type="checkbox" name="service_id[]" value="<?=$sid?>" class="svc-check" id="svc-<?=$sid?>">
                        <label for="svc-<?=$sid?>" style="flex:1; cursor:pointer">
                            <div style="font-weight:700; font-size:14px"><?=e($s['service_name'])?></div>
                            <div style="font-size:12px; color:var(--muted)">₦<?=e(money((float)$s['total']))?></div>
                        </label>
                        <input type="number" min="1" name="quantity[<?=$sid?>]" value="1" class="form-input" style="width:70px; padding:6px 10px">
                    </div>
                <?php endforeach; ?>
            </div>
            
            <div style="margin-top:32px; display:flex; gap:12px">
                <button type="button" class="btn btn-outline" style="flex:1" onclick="document.getElementById('items-dialog').close()">Cancel</button>
                <button class="btn primary" type="submit" style="flex:2; font-weight:700">Update Bundle Items</button>
            </div>
        </form>
    </div>
</dialog>

<div class="package-grid">
    <?php foreach ($packages as $p):
        $tot = compute_package_total($pdo,(int)$p['id']);
        $statusCls = $p['status'] === 'active' ? 'status-active' : 'status-inactive';
    ?>
    <div class="pkg-card">
        <div class="pkg-header">
            <h4 class="pkg-name"><?=e($p['name'])?></h4>
            <span class="pkg-status <?=$statusCls?>"><?=e($p['status'])?></span>
        </div>
        
        <p class="pkg-desc"><?=e($p['description'] ?: 'No description provided.')?></p>
        
        <?php if ($p['discount_type'] !== 'none'): ?>
            <div class="pkg-discount-tag">
                <?=ui_icon('pricing', 14)?>
                Discount: <?=ucfirst($p['discount_type'])?> 
                (<?=$p['discount_type'] === 'percent' ? e((string)$p['discount_value']).'%' : '₦'.e(money((float)$p['discount_value']))?>)
            </div>
        <?php else: ?>
            <div style="height:42px"></div>
        <?php endif; ?>

        <div class="pkg-pricing">
            <div class="pricing-row">
                <span class="price-label">Base Price</span>
                <span class="price-value">₦<?=e(money($tot['base']))?></span>
            </div>
            <div class="pricing-row">
                <span class="price-label">Savings</span>
                <span class="price-value" style="color:#16a34a">- ₦<?=e(money($tot['discount']))?></span>
            </div>
            <div class="pricing-row">
                <span class="price-label" style="color:var(--text); font-weight:800">Bundle Price</span>
                <span class="price-total">₦<?=e(money($tot['total']))?></span>
            </div>
        </div>

        <div class="pkg-actions">
            <button class="btn btn-outline" style="font-size:13px; font-weight:600" 
                    onclick="editPkg(<?=htmlspecialchars(json_encode($p))?>)">
                Edit Details
            </button>
            <button class="btn btn-outline" style="font-size:13px; font-weight:600" 
                    onclick="manageItems(<?=e((string)$p['id'])?>)">
                Manage Items
            </button>
            <form method="post" style="margin:0; grid-column: span 2">
                <?=csrf_field()?>
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="id" value="<?=e((string)$p['id'])?>">
                <button class="btn" style="width:100%; font-size:13px; font-weight:600">
                    <?=$p['status']==='active'?'Deactivate Package':'Activate Package'?>
                </button>
            </form>
            <form method="post" style="margin:0; grid-column: span 2" onsubmit="return confirm('Delete package?')">
                <?=csrf_field()?>
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?=e((string)$p['id'])?>">
                <button class="btn" style="width:100%; font-size:12px; font-weight:600; color:#ef4444; border:none; background:transparent">
                    Delete Permanently
                </button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<script>
const pkgDialog = document.getElementById('pkg-dialog');
const itemsDialog = document.getElementById('items-dialog');
const pkgForm = document.getElementById('pkg-form');
const dtypeSelect = document.getElementById('pkg-dtype');
const tiersGroup = document.getElementById('tiers-group');

dtypeSelect.onchange = function() {
    tiersGroup.style.display = this.value === 'tiered' ? 'block' : 'none';
};

function editPkg(pkg) {
    document.getElementById('modal-title').textContent = 'Edit Package';
    document.getElementById('form-action').value = 'update';
    document.getElementById('pkg-id').value = pkg.id;
    document.getElementById('pkg-name').value = pkg.name;
    document.getElementById('pkg-desc').value = pkg.description || '';
    document.getElementById('pkg-dtype').value = pkg.discount_type;
    document.getElementById('pkg-dval').value = pkg.discount_value;
    document.getElementById('pkg-tiers').value = pkg.discount_tiers_json || '';
    document.getElementById('submit-btn').textContent = 'Update Package';
    tiersGroup.style.display = pkg.discount_type === 'tiered' ? 'block' : 'none';
    pkgDialog.showModal();
}

function manageItems(pkgId) {
    document.getElementById('items-pkg-id').value = pkgId;
    // Note: In a real app, you'd fetch the selected items via AJAX here
    // For now, we'll reset and let the admin check them manually
    document.querySelectorAll('.svc-check').forEach(c => c.checked = false);
    itemsDialog.showModal();
}

document.getElementById('open-pkg').onclick = () => {
    document.getElementById('modal-title').textContent = 'New Package';
    document.getElementById('form-action').value = 'create';
    pkgForm.reset();
    document.getElementById('submit-btn').textContent = 'Create Package';
    tiersGroup.style.display = 'none';
    pkgDialog.showModal();
};

document.querySelectorAll('.close-dialog').forEach(b => {
    b.onclick = () => {
        pkgDialog.close();
        itemsDialog.close();
    }
});

[pkgDialog, itemsDialog].forEach(d => {
    d.onclick = (e) => { if(e.target === d) d.close(); };
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
