<?php
require_once __DIR__ . '/../lib/core.php';
dc_require_login();

header('Content-Type: application/json; charset=utf-8');

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$categoryId = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 0;
$projectId = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;
$year = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
$doorNumber = isset($_GET['door_number']) ? trim($_GET['door_number']) : '';

$category = null;
$project = null;
if ($categoryId > 0) {
    $stmt = dc_db()->prepare('SELECT * FROM door_cert_categories WHERE id=?');
    $stmt->execute(array($categoryId));
    $category = $stmt->fetch();
}
if ($projectId > 0) {
    $stmt = dc_db()->prepare('SELECT * FROM door_cert_projects WHERE id=?');
    $stmt->execute(array($projectId));
    $project = $stmt->fetch();
}

if (!$category || !$project || $doorNumber === '') {
    echo json_encode(array('ok' => false, 'door_id' => '', 'exists' => false));
    exit;
}

$doorId = dc_build_door_id($category['code'], $year, $project['project_number'], $doorNumber);

if ($id > 0) {
    $stmt = dc_db()->prepare('SELECT d.*, c.code category_code, p.project_number FROM door_cert_doors d JOIN door_cert_categories c ON c.id=d.category_id JOIN door_cert_projects p ON p.id=d.project_id WHERE d.id=?');
    $stmt->execute(array($id));
    $existing = $stmt->fetch();
    if ($existing && (int)$existing['category_id'] === $categoryId && (int)$existing['project_id'] === $projectId && (string)$existing['door_number'] === (string)$doorNumber && (string)$year === substr($existing['door_id'], strpos($existing['door_id'], '-') + 1, 4)) {
        $doorId = $existing['door_id'];
    }
}

echo json_encode(array(
    'ok' => true,
    'door_id' => $doorId,
    'exists' => dc_door_id_exists($doorId, $id),
));
