<?php
// submit.php - Final Submission Handler
session_start();

if (!isset($_SESSION['form_data']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
  header("Location: index.php");
  exit();
}

$form = $_SESSION['form_data'];
$agree = isset($_POST['final_agree']);
if (!$agree) {
  die("You must confirm the occupancy agreement to submit the application.");
}

// Generate Reference Number (e.g., S-2025-05-13-0001)
$date = date('Y-m-d');
$counterFile = __DIR__ . "/submissions/count-" . $date . ".txt";
if (!file_exists($counterFile)) {
  file_put_contents($counterFile, "1");
  $count = 1;
} else {
  $count = (int) file_get_contents($counterFile);
  $count++;
  file_put_contents($counterFile, (string)$count);
}
$ref = "S-2025-" . date('m-d') . "-" . str_pad($count, 4, "0", STR_PAD_LEFT);

// Save JSON
$data = $form;
$data['reference'] = $ref;
$jsonFile = __DIR__ . "/submissions/{$ref}.json";
file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT));

// Generate PDF summary
ob_start();
include 'template-review-pdf.php';
$html = ob_get_clean();

require_once __DIR__ . '/assets/dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
file_put_contents(__DIR__ . "/submissions/{$ref}.pdf", $dompdf->output());

// Email setup
require 'mailer-config.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'assets/PHPMailer/src/Exception.php';
require 'assets/PHPMailer/src/PHPMailer.php';
require 'assets/PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);
try {
  $mail->isSMTP();
  $mail->Host = SMTP_HOST;
  $mail->SMTPAuth = true;
  $mail->Username = SMTP_USERNAME;
  $mail->Password = SMTP_PASSWORD;
  $mail->SMTPSecure = SMTP_SECURE;
  $mail->Port = SMTP_PORT;
  $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);

  // Send to applicant
  $mail->addAddress($form['email'], $form['first_name']);
  $mail->Subject = "Tartu College Summer Application {$ref}: {$form['move_in']} to {$form['move_out']}";
  $mail->Body = "Dear {$form['first_name']},\n\nThank you for submitting your summer application.\n\nReference #: {$ref}\nMove-in: {$form['move_in']}\nMove-out: {$form['move_out']}\n\nA PDF copy of your application is attached.";
  $mail->addAttachment("submissions/{$ref}.pdf");
  $mail->send();

  // Send to office
  $mail->clearAddresses();
  $mail->addAddress(ADMIN_EMAIL);
  $mail->Subject = "[Office Copy] Summer Application {$ref} – {$form['first_name']} {$form['last_name']} – {$form['move_in']} to {$form['move_out']}";
  $mail->Body = "Office copy of summer application from {$form['first_name']} {$form['last_name']}. Reference #: {$ref}";
  $mail->addAttachment("submissions/{$ref}.pdf");
  $mail->send();

  // Clear session
  unset($_SESSION['form_data']);
  echo "<h1>Thank you!</h1><p>Your application has been submitted successfully. Reference #: {$ref}</p>";
  echo "<a href='index.php'>Submit Another Application</a>";

} catch (Exception $e) {
  echo "<h1>Error</h1><p>Application failed: {$mail->ErrorInfo}</p>";
}
?>