<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../config/database.php';
header('Content-Type: application/json');
require_customer();

$uid = (int)($_SESSION['user']['id'] ?? 0);
$id = (int)($_GET['id'] ?? 0);
$app = $pdo->prepare('SELECT status FROM applications WHERE id=? AND user_id=?');
$app->execute([$id,$uid]); $row = $app->fetch();
if (!$row) { http_response_code(404); echo json_encode(['error'=>'not found']); exit; }
$status = (string)$row['status'];

$d = $pdo->prepare('SELECT 1 FROM application_details WHERE application_id=?');
$d->execute([$id]); $hasDetails = (bool)$d->fetch();
$a = $pdo->prepare('SELECT 1 FROM application_addons WHERE application_id=?');
$a->execute([$id]); $hasAddons = (bool)$a->fetch();
$p = $pdo->prepare('SELECT status FROM payments WHERE application_id=? ORDER BY id DESC LIMIT 1');
$p->execute([$id]); $pay = $p->fetch();
$paymentSubmitted = (bool)$pay;
$paymentConfirmed = $pay && (($pay['status'] ?? '') === 'confirmed');

echo json_encode([
  'status'=>$status,
  'details'=>$hasDetails,
  'addons'=>$hasAddons,
  'payment_submitted'=>$paymentSubmitted,
  'payment_confirmed'=>$paymentConfirmed
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
