<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Manager Approval PINs';

if (file_exists(__DIR__ . '/../../includes/permission_check.php')) {
    require_once __DIR__ . '/../../includes/permission_check.php';
    if (function_exists('require_permission')) {
        require_permission($pdo, 'role_permissions', 'edit');
    }
}

if (!function_exists('h')) {
    function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('pin_flash')) {
    function pin_flash(string $type, string $message): void {
        $_SESSION['manager_pin_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('pin_get_flash')) {
    function pin_get_flash(): array {
        $items = $_SESSION['manager_pin_flash'] ?? [];
        unset($_SESSION['manager_pin_flash']);
        return $items;
    }
}
if (!function_exists('pin_table_exists')) {
    function pin_table_exists(PDO $pdo, string $table): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = :table
        ");
        $stmt->execute([':table' => $table]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('pin_col_exists')) {
    function pin_col_exists(PDO $pdo, string $table, string $column): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = :table
              AND column_name = :column
        ");
        $stmt->execute([':table' => $table, ':column' => $column]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('pin_user_name_expr')) {
    function pin_user_name_expr(PDO $pdo, string $alias = 'u'): string {
        if (pin_col_exists($pdo, 'users', 'firstname') && pin_col_exists($pdo, 'users', 'lastname')) {
            return "TRIM(CONCAT(COALESCE({$alias}.firstname,''), ' ', COALESCE({$alias}.lastname,'')))";
        }
        if (pin_col_exists($pdo, 'users', 'name')) return "{$alias}.name";
        if (pin_col_exists($pdo, 'users', 'full_name')) return "{$alias}.full_name";
        if (pin_col_exists($pdo, 'users', 'username')) return "{$alias}.username";
        if (pin_col_exists($pdo, 'users', 'email')) return "{$alias}.email";
        return "CONCAT('User #', {$alias}.id)";
    }
}
if (!function_exists('pin_role_label')) {
    function pin_role_label($role): string {
        $role = (int)$role;
        $map = [
            1 => 'Super Admin',
            2 => 'Admin',
            3 => 'Manager',
            4 => 'Front Desk',
            5 => 'Cashier',
            6 => 'Stores',
            7 => 'Accounts',
            8 => 'Housekeeping',
            9 => 'Owner',
            10 => 'User',
        ];
        return $map[$role] ?? 'User';
    }
}
if (!function_exists('ensure_pin_schema')) {
    function ensure_pin_schema(PDO $pdo): void {
        if (!pin_table_exists($pdo, 'users')) {
            throw new RuntimeException('The users table does not exist.');
        }

        if (!pin_col_exists($pdo, 'users', 'approval_pin_hash')) {
            $pdo->exec("ALTER TABLE users ADD COLUMN approval_pin_hash VARCHAR(255) NULL AFTER password");
        }

        if (!pin_col_exists($pdo, 'users', 'approval_pin_set_at')) {
            $pdo->exec("ALTER TABLE users ADD COLUMN approval_pin_set_at DATETIME NULL AFTER approval_pin_hash");
        }

        $pdo->exec("
            CREATE TABLE IF NOT EXISTS manager_approval_log (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                permission_key VARCHAR(120) NULL,
                action_label VARCHAR(255) NULL,
                reference_type VARCHAR(80) NULL,
                reference_id BIGINT UNSIGNED NULL,
                manager_user_id INT UNSIGNED NULL,
                requested_by INT UNSIGNED NULL,
                ip_address VARCHAR(64) NULL,
                user_agent VARCHAR(255) NULL,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_manager_approval_ref (reference_type, reference_id),
                INDEX idx_manager_approval_manager (manager_user_id),
                INDEX idx_manager_approval_created (created_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
    }
}
if (!function_exists('pin_manager_where')) {
    function pin_manager_where(PDO $pdo, string $alias = 'u'): string {
        $parts = [];

        if (pin_col_exists($pdo, 'users', 'user_role')) {
            $parts[] = "{$alias}.user_role IN (1,2,3,9)";
        }

        if (pin_col_exists($pdo, 'users', 'role_key')) {
            $parts[] = "{$alias}.role_key IN ('super_admin','admin','manager','owner')";
        }

        return $parts ? '(' . implode(' OR ', $parts) . ')' : '1=1';
    }
}
if (!function_exists('pin_active_where')) {
    function pin_active_where(PDO $pdo, string $alias = 'u'): string {
        if (pin_col_exists($pdo, 'users', 'active')) return " AND {$alias}.active = 1 ";
        if (pin_col_exists($pdo, 'users', 'is_active')) return " AND {$alias}.is_active = 1 ";
        return "";
    }
}

$errors = [];

try {
    ensure_pin_schema($pdo);
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();
        ensure_pin_schema($pdo);

        $action = (string)($_POST['action'] ?? '');
        $userId = (int)($_POST['user_id'] ?? 0);

        if ($userId <= 0) {
            throw new RuntimeException('Invalid manager selected.');
        }

        $roleWhere = pin_manager_where($pdo, 'u');
        $activeWhere = pin_active_where($pdo, 'u');

        $stmt = $pdo->prepare("
            SELECT u.id
            FROM users u
            WHERE u.id = :id
              AND {$roleWhere}
              {$activeWhere}
            LIMIT 1
        ");
        $stmt->execute([':id' => $userId]);

        if (!$stmt->fetchColumn()) {
            throw new RuntimeException('Selected user is not an active manager/admin/owner approver.');
        }

        if ($action === 'set_pin') {
            $pin = trim((string)($_POST['approval_pin'] ?? ''));
            $confirm = trim((string)($_POST['approval_pin_confirm'] ?? ''));

            if (!preg_match('/^\d{4,8}$/', $pin)) {
                throw new RuntimeException('Approval PIN must be 4 to 8 digits.');
            }

            if ($pin !== $confirm) {
                throw new RuntimeException('PIN confirmation does not match.');
            }

            $hash = password_hash($pin, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare("
                UPDATE users
                SET approval_pin_hash = :hash,
                    approval_pin_set_at = NOW()
                WHERE id = :id
            ");
            $stmt->execute([
                ':hash' => $hash,
                ':id' => $userId,
            ]);

            pin_flash('success', 'Manager approval PIN saved successfully.');
            header('Location: manager_pins.php');
            exit;
        }

        if ($action === 'clear_pin') {
            $stmt = $pdo->prepare("
                UPDATE users
                SET approval_pin_hash = NULL,
                    approval_pin_set_at = NULL
                WHERE id = :id
            ");
            $stmt->execute([':id' => $userId]);

            pin_flash('warning', 'Manager approval PIN cleared.');
            header('Location: manager_pins.php');
            exit;
        }

        throw new RuntimeException('Unknown action.');

    } catch (Throwable $e) {
        pin_flash('danger', $e->getMessage());
        header('Location: manager_pins.php');
        exit;
    }
}

$search = trim((string)($_GET['q'] ?? ''));
$pinStatus = trim((string)($_GET['pin_status'] ?? ''));

$users = [];
$summary = ['approvers' => 0, 'with_pin' => 0, 'without_pin' => 0, 'logs' => 0];
$recentLogs = [];
$flashes = pin_get_flash();

try {
    if (!$errors) {
        $nameExpr = pin_user_name_expr($pdo, 'u');
        $roleWhere = pin_manager_where($pdo, 'u');
        $activeWhere = pin_active_where($pdo, 'u');

        $where = "{$roleWhere} {$activeWhere}";
        $params = [];

        if ($search !== '') {
            $where .= " AND (";
            $bits = [];

            if (pin_col_exists($pdo, 'users', 'firstname')) $bits[] = "u.firstname LIKE :q";
            if (pin_col_exists($pdo, 'users', 'lastname')) $bits[] = "u.lastname LIKE :q";
            if (pin_col_exists($pdo, 'users', 'username')) $bits[] = "u.username LIKE :q";
            if (pin_col_exists($pdo, 'users', 'email')) $bits[] = "u.email LIKE :q";

            if (!$bits) $bits[] = "u.id LIKE :q";

            $where .= implode(' OR ', $bits) . ")";
            $params[':q'] = '%' . $search . '%';
        }

        if ($pinStatus === 'set') {
            $where .= " AND u.approval_pin_hash IS NOT NULL AND u.approval_pin_hash <> ''";
        } elseif ($pinStatus === 'missing') {
            $where .= " AND (u.approval_pin_hash IS NULL OR u.approval_pin_hash = '')";
        }

        $stmt = $pdo->prepare("
            SELECT
                u.id,
                {$nameExpr} AS display_name,
                " . (pin_col_exists($pdo, 'users', 'username') ? "u.username" : "NULL AS username") . ",
                " . (pin_col_exists($pdo, 'users', 'email') ? "u.email" : "NULL AS email") . ",
                " . (pin_col_exists($pdo, 'users', 'phone') ? "u.phone" : "NULL AS phone") . ",
                " . (pin_col_exists($pdo, 'users', 'user_role') ? "u.user_role" : "NULL AS user_role") . ",
                u.approval_pin_set_at,
                CASE WHEN u.approval_pin_hash IS NULL OR u.approval_pin_hash = '' THEN 0 ELSE 1 END AS has_pin
            FROM users u
            WHERE {$where}
            ORDER BY display_name ASC, u.id ASC
            LIMIT 300
        ");
        $stmt->execute($params);
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $stmt = $pdo->query("
            SELECT
                COUNT(*) AS approvers,
                SUM(CASE WHEN approval_pin_hash IS NULL OR approval_pin_hash = '' THEN 0 ELSE 1 END) AS with_pin,
                SUM(CASE WHEN approval_pin_hash IS NULL OR approval_pin_hash = '' THEN 1 ELSE 0 END) AS without_pin
            FROM users u
            WHERE " . pin_manager_where($pdo, 'u') . pin_active_where($pdo, 'u')
        );
        $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $summary['approvers'] = (int)($row['approvers'] ?? 0);
        $summary['with_pin'] = (int)($row['with_pin'] ?? 0);
        $summary['without_pin'] = (int)($row['without_pin'] ?? 0);

        if (pin_table_exists($pdo, 'manager_approval_log')) {
            $summary['logs'] = (int)$pdo->query("SELECT COUNT(*) FROM manager_approval_log")->fetchColumn();

            $managerName = pin_user_name_expr($pdo, 'mu');
            $requestedName = pin_user_name_expr($pdo, 'ru');

            $stmt = $pdo->query("
                SELECT
                    mal.*,
                    {$managerName} AS manager_name,
                    {$requestedName} AS requested_by_name
                FROM manager_approval_log mal
                LEFT JOIN users mu ON mu.id = mal.manager_user_id
                LEFT JOIN users ru ON ru.id = mal.requested_by
                ORDER BY mal.created_at DESC
                LIMIT 20
            ");
            $recentLogs = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load manager PIN data: ' . $e->getMessage();
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band no-print">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-shield-lock"></i> System Security</div>
            <div class="hero-title mt-2">Manager Approval PINs</div>
            <div class="hero-subtitle mt-2">
                Set secure approval PINs for managers, admins, owners and super admins used in sensitive workflows.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="purchase_order_approvals.php" class="btn btn-light me-2">
                <i class="bi bi-shield-check me-2"></i>PO Approvals
            </a>
            <a href="users.php" class="btn btn-outline-light">
                <i class="bi bi-people me-2"></i>Users
            </a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-person-check"></i></div>
            <div><div class="metric-label">Approvers</div><div class="metric-value"><?php echo (int)$summary['approvers']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-key"></i></div>
            <div><div class="metric-label">PIN Set</div><div class="metric-value"><?php echo (int)$summary['with_pin']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-exclamation-triangle"></i></div>
            <div><div class="metric-label">PIN Missing</div><div class="metric-value"><?php echo (int)$summary['without_pin']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-info-subtle text-info"><i class="bi bi-journal-check"></i></div>
            <div><div class="metric-label">Approval Logs</div><div class="metric-value"><?php echo (int)$summary['logs']; ?></div></div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-8">
        <div class="card panel-card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-7">
                        <label class="form-label">Search Approver</label>
                        <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Name / username / email">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">PIN Status</label>
                        <select name="pin_status" class="form-select">
                            <option value="">All</option>
                            <option value="set" <?php echo $pinStatus === 'set' ? 'selected' : ''; ?>>PIN Set</option>
                            <option value="missing" <?php echo $pinStatus === 'missing' ? 'selected' : ''; ?>>PIN Missing</option>
                        </select>
                    </div>
                    <div class="col-md-2 d-grid">
                        <button class="btn btn-primary"><i class="bi bi-funnel me-2"></i>Filter</button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Approval Managers</h5>
                <span class="small text-muted">Roles: Super Admin, Admin, Manager, Owner</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Manager</th>
                            <th>Role</th>
                            <th>Contact</th>
                            <th>PIN Status</th>
                            <th>Set / Reset PIN</th>
                            <th class="text-end">Clear</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$users): ?>
                            <tr><td colspan="6" class="text-center text-muted py-4">No approvers found.</td></tr>
                        <?php else: foreach ($users as $u): ?>
                            <tr>
                                <td>
                                    <strong><?php echo h($u['display_name'] ?: ('User #' . $u['id'])); ?></strong>
                                    <div class="small text-muted">@<?php echo h($u['username'] ?: '—'); ?> • ID <?php echo (int)$u['id']; ?></div>
                                </td>
                                <td>
                                    <span class="badge text-bg-primary"><?php echo h(pin_role_label($u['user_role'])); ?></span>
                                    <div class="small text-muted">Role <?php echo h($u['user_role'] ?: '—'); ?></div>
                                </td>
                                <td>
                                    <?php echo h($u['email'] ?: '—'); ?>
                                    <div class="small text-muted"><?php echo h($u['phone'] ?: ''); ?></div>
                                </td>
                                <td>
                                    <?php if ((int)$u['has_pin'] === 1): ?>
                                        <span class="badge text-bg-success">PIN Set</span>
                                        <div class="small text-muted"><?php echo h($u['approval_pin_set_at'] ?: ''); ?></div>
                                    <?php else: ?>
                                        <span class="badge text-bg-warning">PIN Missing</span>
                                    <?php endif; ?>
                                </td>
                                <td style="min-width:280px">
                                    <form method="post" class="pin-inline-form" autocomplete="off">
                                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                        <input type="hidden" name="action" value="set_pin">
                                        <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                        <div class="input-group input-group-sm">
                                            <input type="password" name="approval_pin" class="form-control pin-input" placeholder="New PIN" inputmode="numeric" pattern="[0-9]*" maxlength="8" required>
                                            <input type="password" name="approval_pin_confirm" class="form-control pin-input" placeholder="Confirm" inputmode="numeric" pattern="[0-9]*" maxlength="8" required>
                                            <button class="btn btn-success"><i class="bi bi-save"></i></button>
                                        </div>
                                        <div class="small text-muted mt-1">4 to 8 digits. Stored securely as a hash.</div>
                                    </form>
                                </td>
                                <td class="text-end">
                                    <?php if ((int)$u['has_pin'] === 1): ?>
                                        <form method="post" onsubmit="return confirm('Clear approval PIN for this manager?');">
                                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                            <input type="hidden" name="action" value="clear_pin">
                                            <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                            <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                                        </form>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="alert alert-info mt-4">
            <strong>Important:</strong> Existing login passwords are not used for approval anymore. Managers must have an approval PIN set here before they can approve.
        </div>
    </div>

    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Recent Approval Logs</h5></div>
            <div class="card-body">
                <?php if (!$recentLogs): ?>
                    <div class="text-muted">No approval logs yet.</div>
                <?php else: ?>
                    <div class="approval-log-list">
                        <?php foreach ($recentLogs as $log): ?>
                            <div class="approval-log-item">
                                <div class="d-flex justify-content-between gap-2">
                                    <strong><?php echo h($log['manager_name'] ?: ('Manager #' . $log['manager_user_id'])); ?></strong>
                                    <span class="small text-muted"><?php echo h(date('d M H:i', strtotime($log['created_at']))); ?></span>
                                </div>
                                <div class="small"><?php echo h($log['action_label'] ?: $log['permission_key']); ?></div>
                                <div class="small text-muted">
                                    Ref: <?php echo h($log['reference_type'] ?: '—'); ?> #<?php echo h($log['reference_id'] ?: '—'); ?>
                                    <?php if (!empty($log['requested_by_name'])): ?> • By <?php echo h($log['requested_by_name']); ?><?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">How It Works</h5></div>
            <div class="card-body">
                <ol class="small mb-0 security-steps">
                    <li>Create users with role Manager, Admin, Owner or Super Admin.</li>
                    <li>Set each manager’s PIN on this page.</li>
                    <li>When approving a PO, select the manager and enter their PIN.</li>
                    <li>The system stores an audit log of who approved what and when.</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.pin-inline-form .pin-input{text-align:center;font-weight:800;letter-spacing:.12rem}
.approval-log-list{display:flex;flex-direction:column;gap:10px}
.approval-log-item{border:1px solid rgba(15,23,42,.08);background:#f8fafc;border-radius:16px;padding:12px}
.security-steps li{margin-bottom:8px}
.table-modern td{vertical-align:middle}
</style>

<script>
document.addEventListener('DOMContentLoaded', function(){
    document.querySelectorAll('.pin-inline-form').forEach(function(form){
        form.addEventListener('submit', function(e){
            const pin = form.querySelector('input[name="approval_pin"]').value.trim();
            const confirm = form.querySelector('input[name="approval_pin_confirm"]').value.trim();

            if (!/^\d{4,8}$/.test(pin)) {
                e.preventDefault();
                alert('PIN must be 4 to 8 digits.');
                return;
            }

            if (pin !== confirm) {
                e.preventDefault();
                alert('PIN confirmation does not match.');
                return;
            }
        });
    });
});
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
