<?php
session_start();
include '../functions.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || !isset($_SESSION['email'])) {
    echo json_encode(['success' => false, 'message' => 'Session expired. Please log in again.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

$input   = json_decode(file_get_contents('php://input'), true) ?? [];
$cot     = trim($input['cot_code'] ?? '');

if ($cot === '') {
    echo json_encode(['success' => false, 'message' => 'Please enter your COT code.']);
    exit;
}

try {
    $stmt = $connect->prepare("SELECT id FROM cot_codes WHERE cot_code = ? AND status = 'Active' LIMIT 1");
    $stmt->bind_param("s", $cot);
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'A server error occurred. Please contact support.']);
    exit;
}

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid or expired COT code. Please check and try again.']);
    exit;
}

$_SESSION['lt_cot_code'] = $cot;
echo json_encode(['success' => true]);
