<?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();

$action = $_POST['action'] ?? '';
if ($action === 'create') {
    ensure_csrf();
    $name = sanitize_str($_POST['service_name'] ?? '');
    $cac = (float)($_POST['cac_fee'] ?? 0);
    $fee = (float)($_POST['service_fee'] ?? 0);
    $comm = (float)($_POST['commission_percent'] ?? 10);
    $stmt = $pdo->prepare('INSERT INTO services (service_name,cac_fee,service_fee,commission_percent,status,created_at) VALUES (?,?,?,?,?,?)');
    $stmt->execute([$name,$cac,$fee,$comm,'active',date('c')]);
    set_flash('success','Service created');
    redirect('/admin/services.php');
}
if ($action === 'update') {
    ensure_csrf();
    $id = (int)($_POST['id'] ?? 0);
    $name = sanitize_str($_POST['service_name'] ?? '');
    $cac = (float)($_POST['cac_fee'] ?? 0);
    $fee = (float)($_POST['service_fee'] ?? 0);
    $comm = (float)($_POST['commission_percent'] ?? 10);
    $stmt = $pdo->prepare('UPDATE services SET service_name=?, cac_fee=?, service_fee=?, commission_percent=? WHERE id=?');
    $stmt->execute([$name,$cac,$fee,$comm,$id]);
    set_flash('success','Service updated');
    redirect('/admin/services.php');
}
if ($action === 'delete') {
    ensure_csrf();
    $id = (int)($_POST['id'] ?? 0);
    $stmt = $pdo->prepare('DELETE FROM services WHERE id=?');
    $stmt->execute([$id]);
    set_flash('success','Service deleted');
    redirect('/admin/services.php');
}
if ($action === 'toggle') {
    ensure_csrf();
    $id = (int)($_POST['id'] ?? 0);
    $svc = $pdo->prepare('SELECT status FROM services WHERE id=?'); $svc->execute([$id]); $svc = $svc->fetch();
    if ($svc) {
        $new = $svc['status']==='active'?'inactive':'active';
        $stmt = $pdo->prepare('UPDATE services SET status=? WHERE id=?');
        $stmt->execute([$new,$id]);
        set_flash('success','Service status updated');
    }
    redirect('/admin/services.php');
}

$services = $pdo->query("SELECT * FROM services WHERE service_name NOT LIKE 'Package:%' AND service_name NOT LIKE 'Plan:%' ORDER BY created_at DESC")->fetchAll();
include __DIR__ . '/../includes/header.php';
?>
<style>
/* Services Page Styles */
.admin-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 40px; gap: 20px; flex-wrap: wrap; }
.admin-title { margin: 0; font-size: 32px; font-weight: 800; color: var(--text); letter-spacing: -0.02em; }
.admin-subtitle { margin: 4px 0 0; color: var(--muted); font-size: 16px; }


/* Service Cards & Table */
.service-card-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 24px; margin-bottom: 48px; }
.svc-card { background: #fff; border: 1px solid var(--border); border-radius: 24px; padding: 32px; position: relative; transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: var(--shadow-sm); }
.svc-card:hover { border-color: var(--primary); transform: translateY(-6px); box-shadow: var(--shadow); }

.svc-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 24px; }
.svc-name { font-size: 20px; font-weight: 700; color: var(--text); margin: 0; }
.svc-status { font-size: 11px; font-weight: 700; text-transform: uppercase; padding: 6px 14px; border-radius: 999px; letter-spacing: 0.05em; }

.svc-pricing { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px; padding: 20px; background: #fcfcfd; border: 1px solid var(--border); border-radius: 16px; }
.price-item { display: flex; flex-direction: column; gap: 4px; }
.price-label { font-size: 11px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; opacity: 0.7; }
.price-value { font-size: 16px; font-weight: 700; color: var(--text); }
.price-total { grid-column: 1 / -1; border-top: 1px solid var(--border); padding-top: 16px; margin-top: 8px; display: flex; justify-content: space-between; align-items: center; }


.svc-actions { display: flex; gap: 8px; margin-top: 16px; }

/* Modal/Dialog Styles */
dialog { border: none; border-radius: 28px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); max-width: 540px; width: 90%; padding: 0; overflow: hidden; background: #fff; }
dialog::backdrop { background: rgba(15, 23, 42, 0.4); backdrop-filter: blur(12px); }
.modal-header { padding: 24px 32px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: #fcfcfd; }
.modal-body { padding: 32px; }
.form-group { margin-bottom: 24px; }
.form-label { display: block; font-size: 13px; font-weight: 700; color: var(--text); margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.05em; opacity: 0.8; }
.form-input { width: 100%; padding: 14px 18px; border: 1px solid var(--border); border-radius: 14px; font-size: 15px; transition: all 0.3s ease; }
.form-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.1); }


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

<div class="admin-header">
    <div>
        <h1 class="admin-title">Service Management</h1>
        <p class="admin-subtitle">Configure standalone services, fees, and referral commissions.</p>
    </div>
    <button id="open-svc" class="btn primary" style="padding:12px 24px; font-weight:600">
        <?=ui_icon('new', 18)?> Add New Service
    </button>
</div>

<!-- Add/Edit Service Dialog -->
<dialog id="svc-dialog">
    <div class="modal-header">
        <h3 style="margin:0; font-size:18px; font-weight:700" id="modal-title">New Service</h3>
        <button id="close-svc" style="background:none; border:none; font-size:24px; cursor:pointer; color:var(--muted)">&times;</button>
    </div>
    <div class="modal-body">
        <form method="post" id="svc-form">
            <?=csrf_field()?>
            <input type="hidden" name="action" id="form-action" value="create">
            <input type="hidden" name="id" id="svc-id" value="">
            
            <div class="form-group">
                <label class="form-label">Service Name</label>
                <input type="text" name="service_name" id="svc-name" class="form-input" placeholder="e.g. Business Name Registration" required>
            </div>
            
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:16px">
                <div class="form-group">
                    <label class="form-label">CAC Fee (₦)</label>
                    <input type="number" step="0.01" name="cac_fee" id="svc-cac" class="form-input" placeholder="0.00" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Service Fee (₦)</label>
                    <input type="number" step="0.01" name="service_fee" id="svc-fee" class="form-input" placeholder="0.00" required>
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">Referral Commission (%)</label>
                <input type="number" step="0.01" name="commission_percent" id="svc-comm" class="form-input" value="10" required>
            </div>
            
            <div style="margin-top:32px; display:flex; gap:12px">
                <button type="button" class="btn btn-outline" style="flex:1" onclick="document.getElementById('svc-dialog').close()">Cancel</button>
                <button class="btn primary" type="submit" style="flex:2" id="submit-btn">Create Service</button>
            </div>
        </form>
    </div>
</dialog>

<div class="service-card-list">
    <?php foreach ($services as $s): 
        $total = (float)$s['cac_fee'] + (float)$s['service_fee'];
        $statusCls = $s['status'] === 'active' ? 'status-active' : 'status-inactive';
    ?>
    <div class="svc-card">
        <div class="svc-header">
            <h4 class="svc-name"><?=e($s['service_name'])?></h4>
            <span class="svc-status <?=$statusCls?>"><?=e($s['status'])?></span>
        </div>
        
        <div class="svc-pricing">
            <div class="price-item">
                <span class="price-label">Statutory (CAC)</span>
                <span class="price-value">₦<?=e(money((float)$s['cac_fee']))?></span>
            </div>
            <div class="price-item">
                <span class="price-label">Service Fee</span>
                <span class="price-value">₦<?=e(money((float)$s['service_fee']))?></span>
            </div>
            <div class="price-total">
                <span class="price-label" style="color:var(--text); font-weight:700">Total Price</span>
                <span style="font-size:18px; font-weight:800; color:var(--primary)">₦<?=e(money($total))?></span>
            </div>
        </div>

        <div style="display:flex; justify-content:space-between; align-items:center">
            <div style="font-size:12px; color:var(--muted)">
                Commission: <strong><?=e((string)($s['commission_percent']??10))?>%</strong>
            </div>
            <div class="svc-actions">
                <button class="btn btn-outline" style="padding:6px 12px; font-size:12px" 
                        onclick="editSvc(<?=htmlspecialchars(json_encode($s))?>)">
                    Edit
                </button>
                <form method="post" style="margin:0">
                    <?=csrf_field()?>
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="id" value="<?=e((string)$s['id'])?>">
                    <button class="btn" style="padding:6px 12px; font-size:12px">
                        <?= $s['status']==='active'?'Disable':'Enable' ?>
                    </button>
                </form>
                <form method="post" style="margin:0" onsubmit="return confirm('Delete service?')">
                    <?=csrf_field()?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?=e((string)$s['id'])?>">
                    <button class="btn" style="padding:6px 12px; font-size:12px; color:#ef4444">Delete</button>
                </form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<script>
const dialog = document.getElementById('svc-dialog');
const openBtn = document.getElementById('open-svc');
const closeBtn = document.getElementById('close-svc');
const form = document.getElementById('svc-form');

function editSvc(svc) {
    document.getElementById('modal-title').textContent = 'Edit Service';
    document.getElementById('form-action').value = 'update';
    document.getElementById('svc-id').value = svc.id;
    document.getElementById('svc-name').value = svc.service_name;
    document.getElementById('svc-cac').value = svc.cac_fee;
    document.getElementById('svc-fee').value = svc.service_fee;
    document.getElementById('svc-comm').value = svc.commission_percent || 10;
    document.getElementById('submit-btn').textContent = 'Update Service';
    dialog.showModal();
}

openBtn.onclick = () => {
    document.getElementById('modal-title').textContent = 'New Service';
    document.getElementById('form-action').value = 'create';
    form.reset();
    document.getElementById('submit-btn').textContent = 'Create Service';
    dialog.showModal();
};

closeBtn.onclick = () => dialog.close();
dialog.onclick = (e) => { if(e.target === dialog) dialog.close(); };
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
