<?php
error_reporting(E_ALL);
ini_set("display_errors", 0);
ini_set("log_errors", 1);

date_default_timezone_set("Australia/Hobart");

$cfg = require __DIR__ . '/config.php';

// HTTP Basic Auth — must be configured in .env
$_au = $cfg['admin_user'] ?? '';
$_ap = $cfg['admin_pass'] ?? '';
if ($_au === '' || $_ap === '' ||
    !isset($_SERVER['PHP_AUTH_USER']) ||
    $_SERVER['PHP_AUTH_USER'] !== $_au ||
    ($_SERVER['PHP_AUTH_PW'] ?? '') !== $_ap) {
    header('WWW-Authenticate: Basic realm="Modulos Contracts Admin"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Authentication required.';
    exit;
}
unset($_au, $_ap);

$dsn = 'mysql:host=' . $cfg['db_host'] . ';dbname=' . $cfg['db_name'] . ';charset=utf8mb4';
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $cfg['db_username'], $cfg['db_password'], $options);
} catch (PDOException $e) {
    error_log('Database connection failed: ' . $e->getMessage());
    http_response_code(500);
    exit('Service unavailable');
}

$app_id_raw = $_GET['id'] ?? '';
$token      = $_GET['token'] ?? '';

$app_id = preg_match('/^\d+$/', $app_id_raw) ? $app_id_raw : '0';

// Fetch applications
$stmt = $pdo->query("SELECT id, reference, client_email FROM applications ORDER BY id DESC");
$applications = $stmt->fetchAll();
?>

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Admin Dashboard - Application Stages</title>
        <link rel="shortcut icon" href="../internal/images/blueprint.ico" type="image/x-icon">

        <meta name="robots" content="noindex">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js" integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q" crossorigin="anonymous"></script>
        <link href="../internal/css/blueprint.css" rel="stylesheet">
        <link href="../internal/css/print.css" rel="stylesheet" media="print">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

    </head>
    <body class="bg-light">
        <nav class="navbar bg-brown-dark brown-light border-bottom border-body d-print-none">
            <div class="container-fluid">
                <span class="navbar-brand brown-light">
                    <img src="../internal/images/blueprint-logo-light.png" alt="Logo" width="30" height="24" class="d-inline-block align-text-top">
                    Modulos Design
                </span>
                <div class="ms-auto d-flex gap-2">
                    <a href="../internal/dashboard.php" class="btn btn-sm btn-outline-light"><i class="bi bi-grid-fill"></i> Dashboard</a>
                </div>
            </div>
        </nav>
        <div class="container my-5">
            <h2 class="mb-4">Applications</h2>
            <table class="table table-bordered">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Reference</th>
                        <th>Client Email</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($applications as $app): ?>
                    <tr>
                        <td><?= $app['id'] ?></td>
                        <td><?= htmlspecialchars($app['reference'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($app['client_email'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                        <td>
                            <a href="edit_application.php?id=<?= $app['id'] ?>" class="btn btn-sm btn-primary">Edit Timeline</a>
                            <a href="progress.php?id=<?= $app['id'] ?>" class="btn btn-sm btn-outline-secondary">View as Client</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </body>
</html>