<?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) ?? [];
$tax   = trim($input['tax_code'] ?? '');

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

try {
    $stmt = $connect->prepare("SELECT id FROM tax_codes WHERE tax_code = ? AND status = 'Active' LIMIT 1");
    $stmt->bind_param("s", $tax);
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();

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

    sendOtp($_SESSION['email'], $_SESSION['lt_amount'] ?? 0);

    $_SESSION['lt_tax_code'] = $tax;
    echo json_encode(['success' => true]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}
