<?php
// create_enquiry.php
declare(strict_types=1);
date_default_timezone_set('Australia/Hobart');

require_once 'connection.php';

// Throw exceptions on SQL errors for clean handling
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    // Start a transaction to avoid two users getting the same number
    $con->begin_transaction();

    // Lock and read current max drg
    $rs = $con->query("SELECT COALESCE(MAX(drg), 0) AS maxdrg FROM details FOR UPDATE");
    $row = $rs->fetch_assoc();
    $next = (int)$row['maxdrg'] + 1;

    // Insert new details row with current timestamp
    $stmt = $con->prepare("INSERT INTO details (drg, enquiry_date) VALUES (?, NOW())");
    $stmt->bind_param('i', $next);
    $stmt->execute();

    // Ensure there is an addresses row so your dashboard JOIN shows it
    // If drg is the PK in addresses, this works without needing other fields
    $stmt2 = $con->prepare("INSERT INTO addresses (drg) VALUES (?) ON DUPLICATE KEY UPDATE drg = drg");
    $stmt2->bind_param('i', $next);
    $stmt2->execute();

    $con->commit();

    // Send the user straight to the client brief
    header("Location: client-brief.php?drg={$next}");
    exit;

} catch (Throwable $e) {
    // Roll back and show a simple error
    if ($con->errno === 0) {
        // If we did not reach MySQL yet, nothing to roll back
    } else {
        @$con->rollback();
    }
    http_response_code(500);
    echo "<h1>Error creating enquiry</h1>";
    echo "<pre>" . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . "</pre>";
    exit;
}
