<?php
require_once __DIR__ . '/header.php';
perms_require('manage_facilities');

$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_require();

    if (isset($_POST['create_facility'])) {
        $name    = v_clean_string($_POST['name'] ?? '', 100);
        $code    = strtoupper(v_clean_string($_POST['code'] ?? '', 20));
        $address = v_clean_string($_POST['address'] ?? '', 255);
        $city    = v_clean_string($_POST['city'] ?? '', 100);
        $country = v_clean_string($_POST['country'] ?? '', 100);
        $email   = v_clean_string($_POST['contact_email'] ?? '', 120);
        $phone   = v_clean_string($_POST['contact_phone'] ?? '', 40);

        if ($name === '') {
            $err = 'Facility name is required.';
        } else {
            try {
                $pdo->prepare('INSERT INTO facilities (name, code, address, city, country, contact_email, contact_phone) VALUES (?, ?, ?, ?, ?, ?, ?)')
                    ->execute([$name, $code ?: null, $address ?: null, $city ?: null, $country ?: null, $email ?: null, $phone ?: null]);
                audit_log($pdo, 'facility_create', ['name' => $name, 'code' => $code]);
                $msg = 'Facility created.';
            } catch (Throwable $e) {
                if (str_contains($e->getMessage(), 'Duplicate')) {
                    $err = 'A facility with that code already exists.';
                } else {
                    $err = 'Could not create facility.';
                    error_log('facility create: ' . $e->getMessage());
                }
            }
        }
    }
    elseif (isset($_POST['update_facility'])) {
        $id      = v_int($_POST['facility_id'] ?? 0, 1);
        $name    = v_clean_string($_POST['name'] ?? '', 100);
        $code    = strtoupper(v_clean_string($_POST['code'] ?? '', 20));
        $address = v_clean_string($_POST['address'] ?? '', 255);
        $city    = v_clean_string($_POST['city'] ?? '', 100);
        $country = v_clean_string($_POST['country'] ?? '', 100);
        $email   = v_clean_string($_POST['contact_email'] ?? '', 120);
        $phone   = v_clean_string($_POST['contact_phone'] ?? '', 40);

        if ($id > 0 && $name !== '') {
            try {
                $pdo->prepare('UPDATE facilities SET name=?, code=?, address=?, city=?, country=?, contact_email=?, contact_phone=? WHERE id=?')
                    ->execute([$name, $code ?: null, $address ?: null, $city ?: null, $country ?: null, $email ?: null, $phone ?: null, $id]);
                audit_log($pdo, 'facility_update', ['id' => $id, 'name' => $name, 'code' => $code]);
                $msg = 'Facility updated.';
            } catch (Throwable $e) {
                $err = str_contains($e->getMessage(), 'Duplicate')
                    ? 'That facility code is already used by another facility.'
                    : 'Could not update facility.';
            }
        }
    }
    elseif (isset($_POST['delete_facility'])) {
        $id = v_int($_POST['delete_facility'], 1);
        // Block delete if it has candidates, users, forms, or exams
        $c1 = $pdo->prepare("SELECT COUNT(*) c FROM candidates WHERE facility_id = ? AND deleted_at IS NULL");
        $c1->execute([$id]); $cCand = (int)$c1->fetch()['c'];
        $c2 = $pdo->prepare("SELECT COUNT(*) c FROM users WHERE facility_id = ?");
        $c2->execute([$id]); $cUser = (int)$c2->fetch()['c'];
        $c3 = $pdo->prepare("SELECT COUNT(*) c FROM forms WHERE facility_id = ? AND deleted_at IS NULL");
        $c3->execute([$id]); $cForm = (int)$c3->fetch()['c'];

        if ($cCand + $cUser + $cForm > 0) {
            $err = "Cannot delete: this facility has $cCand candidates, $cUser users, $cForm forms attached. Move or delete them first.";
        } else {
            $pdo->prepare("UPDATE facilities SET deleted_at = NOW() WHERE id = ?")->execute([$id]);
            audit_log($pdo, 'facility_delete', ['id' => $id]);
            $msg = 'Facility moved to trash.';
        }
    }
    elseif (isset($_POST['restore_facility'])) {
        $id = v_int($_POST['restore_facility'], 1);
        $pdo->prepare("UPDATE facilities SET deleted_at = NULL WHERE id = ?")->execute([$id]);
        audit_log($pdo, 'facility_restore', ['id' => $id]);
        $msg = 'Facility restored.';
    }
}

$showDeleted = isset($_GET['show_deleted']) && $_GET['show_deleted'] === '1';
$where = $showDeleted ? '' : 'WHERE deleted_at IS NULL';
$facilities = $pdo->query("SELECT * FROM facilities $where ORDER BY name")->fetchAll();
?>
<h2>Facilities / Institutes</h2>
<p class="muted">Each facility is an independent institute with its own candidates, examiners, forms, and exams. The <strong>short code</strong> appears in auto-generated barcodes (e.g. <code>MED-2024GMD01</code>).</p>

<?php if ($msg): ?><div class="alert alert-success"><?php echo h($msg); ?></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger"><?php echo h($err); ?></div><?php endif; ?>

<h3>Add New Facility</h3>
<form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="create_facility" value="1">
    <div class="form-row">
        <div class="field"><label>Name *</label><input type="text" name="name" required placeholder="Main OSCE Centre"></div>
        <div class="field"><label>Short Code (3–10 chars)</label><input type="text" name="code" maxlength="20" placeholder="MOC" style="text-transform:uppercase;"></div>
        <div class="field"><label>City</label><input type="text" name="city" placeholder="Abu Dhabi"></div>
        <div class="field"><label>Country</label><input type="text" name="country" placeholder="UAE"></div>
    </div>
    <div class="form-row">
        <div class="field"><label>Address</label><input type="text" name="address"></div>
        <div class="field"><label>Contact Email</label><input type="email" name="contact_email"></div>
        <div class="field"><label>Contact Phone</label><input type="text" name="contact_phone"></div>
    </div>
    <button type="submit" class="btn btn-primary">Add Facility</button>
</form>

<h3 class="mt-3">Existing Facilities</h3>
<p class="muted">
    <a href="facilities.php?show_deleted=<?php echo $showDeleted ? '0' : '1'; ?>" class="btn btn-sm">
        <?php echo $showDeleted ? '◀ Hide deleted' : '🗑 Show deleted'; ?>
    </a>
</p>
<div class="table-wrap">
<table class="data">
    <thead><tr><th>ID</th><th>Name</th><th>Code</th><th>City</th><th>Country</th><th>Email</th><th>Phone</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($facilities as $f): ?>
        <tr<?php if ($f['deleted_at']) echo ' style="opacity:.55"'; ?>>
            <form method="post">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="update_facility" value="1">
                <input type="hidden" name="facility_id" value="<?php echo (int)$f['id']; ?>">

                <td data-label="ID"><?php echo (int)$f['id']; ?></td>
                <td data-label="Name"><input type="text" name="name" value="<?php echo h($f['name']); ?>"></td>
                <td data-label="Code"><input type="text" name="code" value="<?php echo h($f['code'] ?? ''); ?>" maxlength="20" style="text-transform:uppercase; max-width:120px;"></td>
                <td data-label="City"><input type="text" name="city" value="<?php echo h($f['city'] ?? ''); ?>"></td>
                <td data-label="Country"><input type="text" name="country" value="<?php echo h($f['country'] ?? ''); ?>"></td>
                <td data-label="Email"><input type="email" name="contact_email" value="<?php echo h($f['contact_email'] ?? ''); ?>"></td>
                <td data-label="Phone"><input type="text" name="contact_phone" value="<?php echo h($f['contact_phone'] ?? ''); ?>"></td>
                <td data-label="Status"><?php echo $f['deleted_at'] ? '<span class="badge badge-timeout">deleted</span>' : '<span class="badge badge-submitted">active</span>'; ?></td>
                <td>
                    <button type="submit" class="btn btn-sm">Save</button>
                    <?php if ($f['deleted_at']): ?>
                        <button type="submit" name="restore_facility" value="<?php echo (int)$f['id']; ?>" class="btn btn-sm">Restore</button>
                    <?php else: ?>
                        <button type="submit" name="delete_facility" value="<?php echo (int)$f['id']; ?>" class="btn btn-sm btn-danger"
                                onclick="return confirm('Delete this facility?');">Delete</button>
                    <?php endif; ?>
                </td>
            </form>
            <td style="display:none;"></td><!-- closes row for the form trick -->
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<small class="muted">Address is shown on the candidate's profile; not all fields are required.</small>

<?php require __DIR__ . '/footer.php'; ?>
