<?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:/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['father_name'] ?? '';
                $motherName = $data['mother_name'] ?? '';
                $currentAddress = $data['current_address'] ?? '';
                $permanentAddress = $data['permanent_address'] ?? '';
                $previousTin = $data['previous_tin'] ?? '';
                $status = $data['status'] ?? '';
                $date = $data['date'] ?? '';
                $circle = $data['tax_office']['circle'] ?? '';
                $zone = $data['tax_office']['zone'] ?? '';
                $taxOfficeAddress = $data['tax_office']['address'] ?? '';
                $phone = $data['tax_office']['phone'] ?? '';
                $fullTaxOfficeAddress = $data['tax_office']['full_address'] ?? '';
                $zone1 = $data['tax_office']['zone1'] ?? '';
                $qrcode = $data['qr_code'] ?? '';

                // 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();
}
?>
