<?php
session_start();
error_reporting(1);
include('includes/db.php');
include('includes/config.php');

// Ensure user is logged in
if (!isset($_SESSION['alogin'])) {
    header('location:login.php');
    exit();
}

// Check if TIN is provided
if (isset($_POST['tin'])) {
    $tin = mysqli_real_escape_string($link, $_POST['tin']);

    // Fetch user information
    $id = $_SESSION['alogin'];
    $stmt = $link->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->bind_param("s", $id);
    $stmt->execute();
    $userResult = $stmt->get_result();
    $user = $userResult->fetch_assoc();

    if (!$user) {
        echo '<script>alert("User not found. Please log in again.")</script>';
        die();
    }

    $email = $user['email'];
    $balance = $user['balance'];

    // Fetch control pricing
    $controlResult = mysqli_query($link, "SELECT * FROM control");
    $controlData = mysqli_fetch_assoc($controlResult);

    $tin_price = $controlData['tin'];

    // Check balance
    if ($balance >= $tin_price) {
        // Initialize cURL for API call
        $curl = curl_init();
        $apiUrl = "https://maxzoneofficial.shop/TIN/tin.php?key=MaX-ZoNe-g5xCDrocWGLH&tin=$tin";
        curl_setopt_array($curl, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_FOLLOWLOCATION => true,
        ]);

        $response = curl_exec($curl);
        curl_close($curl);

        if ($response === false) {
            echo '<script>alert("API call failed. Please try again.")</script>';
            die();
        }

        $data = json_decode($response, true);
        if (isset($data['data'])) {
            $data = $data['data'];

            // Ensure required fields are present
            if (!empty($data['tin']) && !empty($data['name'])) {
                // Deduct balance
                $stmt = $link->prepare("UPDATE users SET balance = balance - ? WHERE email = ?");
                $stmt->bind_param("ds", $tin_price, $email);
                $stmt->execute();

                // Assigning values with fallback
                $tinNumber = $data['tin'] ?? '';
                $name = $data['name'] ?? '';
                $fatherName = $data['fatherName'] ?? '';
                $motherName = $data['motherName'] ?? '';
                $currentAddress = $data['currentAddress'] ?? '';
                $permanentAddress = $data['permanentAddress'] ?? '';
                $previousTin = $data['previousTin'] ?? '';
                $status = $data['status'] ?? '';
                $date = $data['date'] ?? '';
                $circle = $data['taxOffice']['circle'] ?? '';
                $zone = $data['taxOffice']['zone'] ?? '';
                $taxOfficeAddress = $data['taxOffice']['address'] ?? '';
                $phone = $data['taxOffice']['phone'] ?? '';
                $fullTaxOfficeAddress = $data['taxOffice']['fullAddress'] ?? '';
                $zone1 = $data['taxOffice']['zone1'] ?? '';
                $qrcode = $data['qrCode'] ?? '';

                // Render HTML output
                include 'tin_certificate_template.php';
            } else {
                echo '<script>alert("TIN information not found. Please check your input.")</script>';
                die();
            }
        } else {
            echo '<script>alert("Invalid API response.")</script>';
            die();
        }
    } else {
        echo '<script>alert("Insufficient balance. Please recharge.")</script>';
        die();
    }
} else {
    echo '<script>alert("Please provide a TIN.")</script>';
    die();
}
?>
