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

date_default_timezone_set("Australia/Hobart");
ini_set("default_charset", "UTF-8");
mb_internal_encoding("UTF-8");

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

$_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);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/vendor/autoload.php';
$cfg = require __DIR__ . '/config.php';

$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 = $_POST['application_id'];
$title = $_POST['title'];
$desc = $_POST['description'];

// Save stage
$stmt = $pdo->prepare("INSERT INTO application_stages (application_id, title, description) VALUES (?, ?, ?)");
$stmt->execute([$app_id, $title, $desc]);

// Fetch client email
$stmt = $pdo->prepare("SELECT client_email FROM applications WHERE id = ?");
$stmt->execute([$app_id]);
$email = $stmt->fetchColumn();



function sendStageEmail($to, $title, $desc, $viewUrl) {
    global $cfg;

    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host       = $cfg['smtp_host'];
    $mail->SMTPAuth   = true;
    $mail->Username   = $cfg['smtp_username'];
    $mail->Password   = $cfg['smtp_password'];
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = $cfg['smtp_port'];

    $mail->setFrom($cfg['from_address'], $cfg['dev_company']);
    $mail->addAddress($to);
    $mail->isHTML(true);

    $subject = "Council Application Progress Update";
    $html = <<<HTML
<p>Hello,</p>
<p>Your application has reached a new stage: <strong>{$title}</strong></p>
<p>{$desc}</p>
<p><a href="{$viewUrl}" class="btn btn-primary">View Application Progress</a></p>
<p>Kind regards,<br>{$cfg['dev_name']}<br>{$cfg['dev_company']}</p>
HTML;

    $mail->Subject = $subject;
    $mail->Body    = $html;
    $mail->AltBody = "New update: $title\n\n$desc\n\nView: $viewUrl";

    $mail->send();
}

// Redirect back to admin dashboard
header("Location: admin_dashboard.php");