<?php
/**
 * Master data: Processes (e.g. "Monthly Revenue Summary")
 * Belongs to a Client. Reports live under a Process.
 */
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);

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

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

        $errors = [];
        if (!$data['client_id'])  $errors[] = 'Client is required.';
        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 _ -';

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

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

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

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

$pageTitle = 'Processes';
require __DIR__ . '/../includes/header.php';

$clients = $pdo->query("
    SELECT c.id, c.name, c.code, v.name AS vertical_name
    FROM clients c JOIN verticals v ON v.id = c.vertical_id
    WHERE c.deleted_at IS NULL ORDER BY v.name, c.name
")->fetchAll();

if ($action === 'new' || $action === 'edit') {
    $row = ['id'=>0,'client_id'=>0,'name'=>'','code'=>'','description'=>'','status'=>'active'];
    if ($action === 'edit' && $id) {
        $stmt = $pdo->prepare('SELECT * FROM processes WHERE id=? AND deleted_at IS NULL');
        $stmt->execute([$id]);
        $row = $stmt->fetch() ?: $row;
        if (!$row['id']) { flash('error','Process not found.'); redirect('/admin/processes.php'); }
    }
?>
<div class="page-header"><div class="container-xl">
    <h2 class="page-title"><?= $action === 'edit' ? 'Edit process' : 'New process' ?></h2>
    <div class="text-secondary">A process belongs to a client. Reports live under a process.</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/processes.php?action=save')) ?>">
    <?= csrf_field() ?>
    <input type="hidden" name="id" value="<?= (int) $row['id'] ?>">
    <div class="row g-3">
        <div class="col-md-6">
            <label class="form-label required">Client</label>
            <select name="client_id" class="form-select" required>
                <option value="">-- choose --</option>
                <?php foreach ($clients as $c): ?>
                    <option value="<?= (int) $c['id'] ?>" <?= $row['client_id'] == $c['id'] ? 'selected' : '' ?>>
                        <?= e($c['name']) ?> (<?= e($c['code']) ?>) &middot; <?= e($c['vertical_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-6">
            <label class="form-label required">Name</label>
            <input type="text" name="name" class="form-control" required maxlength="200" value="<?= e($row['name']) ?>">
        </div>
        <div class="col-md-3">
            <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="REV-MONTHLY">
        </div>
        <div class="col-md-3">
            <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-12">
            <label class="form-label">Description</label>
            <textarea name="description" class="form-control" rows="3" maxlength="2000"><?= e($row['description']) ?></textarea>
        </div>
    </div>
    <div class="form-footer d-flex gap-2">
        <a href="<?= e(url('/admin/processes.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 {
    $q = trim((string) input('q'));
    $clientFilter = (int) input('client_id');
    $params = [];
    $where = 'WHERE p.deleted_at IS NULL';
    if ($q !== '') { $where .= ' AND (p.name LIKE ? OR p.code LIKE ?)'; $params[]="%$q%"; $params[]="%$q%"; }
    if ($clientFilter) { $where .= ' AND p.client_id = ?'; $params[]=$clientFilter; }
    $stmt = $pdo->prepare("
        SELECT p.*, c.name AS client_name, c.code AS client_code, v.name AS vertical_name,
               (SELECT COUNT(*) FROM reports r WHERE r.process_id = p.id AND r.deleted_at IS NULL) AS report_count
        FROM processes p
        JOIN clients   c ON c.id = p.client_id
        JOIN verticals v ON v.id = c.vertical_id
        $where
        ORDER BY c.name, p.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">Processes</h2>
            <div class="text-secondary">A process holds Reports for a specific client.</div>
        </div>
        <div class="col-auto">
            <a href="<?= e(url('/admin/processes.php?action=new')) ?>" class="btn btn-primary">
                <i class="ti ti-plus me-1"></i>New process
            </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) ?>">
                <select name="client_id" class="form-select" style="max-width:240px">
                    <option value="">All clients</option>
                    <?php foreach ($clients as $c): ?>
                        <option value="<?= (int) $c['id'] ?>" <?= $clientFilter == $c['id'] ? 'selected':'' ?>><?= e($c['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <button class="btn"><i class="ti ti-search"></i></button>
                <?php if ($q !== '' || $clientFilter): ?><a href="<?= e(url('/admin/processes.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>Process</th><th>Code</th><th>Client</th><th>Vertical</th>
                    <th>Status</th><th>Reports</th><th class="w-1"></th>
                </tr></thead>
                <tbody>
                <?php if (!$rows): ?>
                    <tr><td colspan="7" class="text-center text-secondary py-4">No processes yet.</td></tr>
                <?php else: foreach ($rows as $r): ?>
                    <tr>
                        <td><strong><?= e($r['name']) ?></strong></td>
                        <td><code><?= e($r['code']) ?></code></td>
                        <td><?= e($r['client_name']) ?></td>
                        <td><?= e($r['vertical_name']) ?></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['report_count'] ?></span></td>
                        <td>
                            <div class="btn-list flex-nowrap">
                                <a href="<?= e(url('/admin/processes.php?action=edit&id=' . $r['id'])) ?>" class="btn btn-sm">
                                    <i class="ti ti-edit"></i>
                                </a>
                                <form method="POST" action="<?= e(url('/admin/processes.php?action=delete&id=' . $r['id'])) ?>"
                                      onsubmit="return confirm('Archive process \'<?= e($r['name']) ?>\'?');">
                                    <?= 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';
