<?php
/**
 * Master data: Verticals (Coding / Billing / AR / ...)
 *
 *   GET                       -> list
 *   GET ?action=new           -> create form
 *   GET ?action=edit&id=X     -> edit form
 *   POST ?action=save         -> insert / update
 *   POST ?action=delete&id=X  -> soft delete
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');

$pdo    = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';
$id     = (int) ($_GET['id'] ?? $_POST['id'] ?? 0);

/* ---------------------------------------------------------- POST handlers */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();

    if ($action === 'save') {
        $data = [
            'name'        => trim((string) input('name')),
            'code'        => strtoupper(trim((string) input('code'))),
            'description' => trim((string) input('description')),
            'status'      => in_array(input('status'), ['active','inactive'], true) ? input('status') : 'active',
            'module'      => in_array(input('module'), ['coding','ar','billing'], true) ? (string) input('module') : null,
        ];

        $errors = [];
        if ($data['name'] === '')                   $errors[] = 'Name is required.';
        if (!preg_match('/^[A-Z0-9_-]{2,50}$/', $data['code']))
            $errors[] = 'Code must be 2-50 chars, A-Z 0-9 _ - only.';

        if (!$errors) {
            $dup = $pdo->prepare('SELECT id FROM verticals WHERE code = ? AND id <> ? AND deleted_at IS NULL');
            $dup->execute([$data['code'], $id]);
            if ($dup->fetch()) $errors[] = 'A vertical with that code already exists.';
        }

        if ($errors) {
            foreach ($errors as $e) flash('error', $e);
            redirect('/admin/verticals.php?action=' . ($id ? 'edit&id=' . $id : 'new'));
        }

        if ($id) {
            $before = $pdo->query("SELECT * FROM verticals WHERE id = $id")->fetch();
            $pdo->prepare(
                'UPDATE verticals SET name=?, code=?, description=?, status=?, module=?, updated_at=NOW() WHERE id=?'
            )->execute([$data['name'], $data['code'], $data['description'], $data['status'], $data['module'], $id]);
            audit_log('vertical.update', 'vertical', $id, $before, $data);
            flash('success', 'Vertical updated.');
        } else {
            $pdo->prepare(
                'INSERT INTO verticals (name,code,description,status,module,created_at,updated_at)
                 VALUES (?,?,?,?,?,NOW(),NOW())'
            )->execute([$data['name'], $data['code'], $data['description'], $data['status'], $data['module']]);
            $newId = (int) $pdo->lastInsertId();
            audit_log('vertical.create', 'vertical', $newId, null, $data);
            flash('success', 'Vertical created.');
        }
        redirect('/admin/verticals.php');
    }

    if ($action === 'delete' && $id) {
        $pdo->prepare('UPDATE verticals SET deleted_at=NOW(), status=? WHERE id=?')->execute(['inactive', $id]);
        audit_log('vertical.delete', 'vertical', $id);
        flash('success', 'Vertical archived.');
        redirect('/admin/verticals.php');
    }
}

/* ---------------------------------------------------------- GET: render */
$pageTitle = 'Verticals';
require __DIR__ . '/../includes/header.php';

if ($action === 'new' || $action === 'edit') {
    $row = ['id' => 0, 'name' => '', 'code' => '', 'description' => '', 'status' => 'active', 'module' => ''];
    if ($action === 'edit' && $id) {
        $stmt = $pdo->prepare('SELECT * FROM verticals WHERE id=? AND deleted_at IS NULL');
        $stmt->execute([$id]);
        $row = $stmt->fetch() ?: $row;
        if (!$row['id']) { flash('error', 'Vertical not found.'); redirect('/admin/verticals.php'); }
    }
?>
<div class="page-header">
    <div class="container-xl">
        <h2 class="page-title"><?= $action === 'edit' ? 'Edit vertical' : 'New vertical' ?></h2>
        <div class="text-secondary">Top of the hierarchy. Verticals contain Clients.</div>
    </div>
</div>
<div class="page-body"><div class="container-xl">
<div class="card"><div class="card-body">
<form method="POST" action="<?= e(url('/admin/verticals.php?action=save')) ?>">
    <?= csrf_field() ?>
    <input type="hidden" name="id" value="<?= (int) $row['id'] ?>">
    <div class="row g-3">
        <div class="col-md-8">
            <label class="form-label required">Name</label>
            <input type="text" name="name" class="form-control" required maxlength="150" value="<?= e($row['name']) ?>">
        </div>
        <div class="col-md-4">
            <label class="form-label required">Code</label>
            <input type="text" name="code" class="form-control text-uppercase" required maxlength="50" value="<?= e($row['code']) ?>" placeholder="BILLING">
            <div class="form-hint">A-Z 0-9 _ - only. 2-50 chars.</div>
        </div>
        <div class="col-12">
            <label class="form-label">Description</label>
            <textarea name="description" class="form-control" rows="3" maxlength="2000"><?= e($row['description']) ?></textarea>
        </div>
        <div class="col-md-4">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
                <option value="active"   <?= $row['status'] === 'active'   ? 'selected' : '' ?>>Active</option>
                <option value="inactive" <?= $row['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option>
            </select>
        </div>
        <div class="col-md-4">
            <label class="form-label">Workflow module</label>
            <select name="module" class="form-select">
                <option value="">None (no work module)</option>
                <option value="coding"  <?= ($row['module'] ?? '') === 'coding'  ? 'selected' : '' ?>>Coding — chart workflow (facilities, charts, audit, deliverables)</option>
                <option value="ar"      <?= ($row['module'] ?? '') === 'ar'      ? 'selected' : '' ?>>AR / Collections</option>
                <option value="billing" <?= ($row['module'] ?? '') === 'billing' ? 'selected' : '' ?>>Billing</option>
            </select>
            <div class="form-hint">Set to <strong>Coding</strong> to run the full chart workflow (facilities » providers » charts » audit » deliverables) for this vertical, independently of the main Coding vertical.</div>
        </div>
    </div>
    <div class="form-footer d-flex gap-2">
        <a href="<?= e(url('/admin/verticals.php')) ?>" class="btn btn-link">Cancel</a>
        <button type="submit" class="btn btn-primary"><i class="ti ti-check me-1"></i>Save</button>
    </div>
</form>
</div></div>
</div></div>
<?php
} else {
    /* List */
    $q = trim((string) input('q'));
    $params = [];
    $where = 'WHERE deleted_at IS NULL';
    if ($q !== '') {
        $where .= ' AND (name LIKE ? OR code LIKE ?)';
        $params[] = "%$q%"; $params[] = "%$q%";
    }
    $stmt = $pdo->prepare("SELECT v.*,
                                  (SELECT COUNT(*) FROM clients c WHERE c.vertical_id = v.id AND c.deleted_at IS NULL) AS client_count
                           FROM verticals v $where ORDER BY v.name LIMIT 200");
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
?>
<div class="page-header">
    <div class="container-xl">
        <div class="row align-items-center">
            <div class="col">
                <h2 class="page-title">Verticals</h2>
                <div class="text-secondary">Top of the hierarchy. Verticals contain Clients.</div>
            </div>
            <div class="col-auto">
                <a href="<?= e(url('/admin/verticals.php?action=new')) ?>" class="btn btn-primary">
                    <i class="ti ti-plus me-1"></i>New vertical
                </a>
            </div>
        </div>
    </div>
</div>
<div class="page-body"><div class="container-xl">
    <div class="card">
        <div class="card-header">
            <form method="GET" class="d-flex w-100 gap-2">
                <input type="text" name="q" class="form-control" placeholder="Search by name or code..." value="<?= e($q) ?>">
                <button class="btn"><i class="ti ti-search"></i></button>
                <?php if ($q !== ''): ?><a href="<?= e(url('/admin/verticals.php')) ?>" class="btn btn-ghost-secondary">Clear</a><?php endif; ?>
            </form>
        </div>
        <div class="table-responsive">
            <table class="table table-vcenter card-table">
                <thead><tr>
                    <th>Name</th><th>Code</th><th>Module</th><th>Status</th><th>Clients</th><th>Created</th><th class="w-1"></th>
                </tr></thead>
                <tbody>
                <?php if (!$rows): ?>
                    <tr><td colspan="7" class="text-center text-secondary py-4">No verticals match.</td></tr>
                <?php else: foreach ($rows as $r): ?>
                    <tr>
                        <td><strong><?= e($r['name']) ?></strong>
                            <?php if ($r['description']): ?><div class="text-secondary small"><?= e(mb_strimwidth($r['description'], 0, 100, '...')) ?></div><?php endif; ?>
                        </td>
                        <td><code><?= e($r['code']) ?></code></td>
                        <td><?php $mod = $r['module'] ?? ''; if ($mod): ?><span class="badge bg-<?= $mod==='coding'?'purple':($mod==='ar'?'azure':'teal') ?>-lt"><?= e($mod) ?></span><?php else: ?><span class="text-secondary small">—</span><?php endif; ?></td>
                        <td>
                            <?php if ($r['status'] === 'active'): ?>
                                <span class="badge bg-success-lt">active</span>
                            <?php else: ?>
                                <span class="badge bg-secondary-lt">inactive</span>
                            <?php endif; ?>
                        </td>
                        <td><span class="badge bg-blue-lt"><?= (int) $r['client_count'] ?></span></td>
                        <td class="text-secondary"><?= e(fmt_date($r['created_at'])) ?></td>
                        <td>
                            <div class="btn-list flex-nowrap">
                                <a href="<?= e(url('/admin/verticals.php?action=edit&id=' . $r['id'])) ?>" class="btn btn-sm">
                                    <i class="ti ti-edit"></i>
                                </a>
                                <form method="POST" action="<?= e(url('/admin/verticals.php?action=delete&id=' . $r['id'])) ?>"
                                      onsubmit="return confirm('Archive vertical \'<?= e($r['name']) ?>\'? Clients under it stay in place.');">
                                    <?= csrf_field() ?>
                                    <button class="btn btn-sm btn-ghost-danger"><i class="ti ti-trash"></i></button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div></div>
<?php
}
require __DIR__ . '/../includes/footer.php';
