<?php
session_start();
include('con.php');
include('header.php');

if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit;
}

$username = $_SESSION['username'];
$errorMsg = $successMsg = "";

// 1. FETCH USER DATA
$udata = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM members WHERE username='$username'"));
$wallet = floatval($udata['balance']);
$user_id = $udata['user_id'];
$site_id = $udata['site_id'];
$parent_id = $udata['parent_id'];
$usertype = $udata['usertype'];
$name = $udata['name'];

// 2. FETCH SERVICE FEE
$feeRow = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='dl_gf_instant'"));
$fee = floatval($feeRow['rate']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['dlno'])) {

    $dlno = strtoupper(preg_replace('/\s+/', '', $_POST['dlno']));
    $dob = trim($_POST['dob']);
    $cardtype = intval($_POST['cardtype']);

    // DUPLICATE CHECK (Now checking the new dl_history table)
    $check = mysqli_query($ahk_conn, "SELECT id FROM dl_history WHERE number='$dlno'");
    
    if (mysqli_num_rows($check) > 0) {
        $errorMsg = "Already downloaded this DL.";
    } elseif ($wallet < $fee) {
        $errorMsg = "Insufficient wallet balance.";
    } else {

        $api_key = "901aaa27a842e8f0a8976f914505c0";
        $api_url = "https://www.apizone.info/api/dl_pdf/dlprint.php?api_key=$api_key&dlno=$dlno&dob=$dob&cardtype=$cardtype";

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 40,
            CURLOPT_FOLLOWLOCATION => true
        ]);

        $response = curl_exec($ch);

        if ($response === false) {
            $errorMsg = "API Error: " . curl_error($ch);
        } else {
            $data = json_decode($response, true);
            $status = (string)($data['status'] ?? '');
            $message = $data['message'] ?? 'Unknown response';

            if ($status === "404") {
                $errorMsg = $message;
            } elseif ($status === "200" && !empty($data['pdf'])) {

                $pdfBase64 = $data['pdf'];
                if (strpos($pdfBase64, ',') !== false) {
                    $pdfBase64 = explode(',', $pdfBase64, 2)[1];
                }

                $pdfContent = base64_decode($pdfBase64);

                if ($pdfContent === false || strlen($pdfContent) < 1000) {
                    $errorMsg = "Invalid PDF data received.";
                } else {

                    // 5. DIRECTORY SETUP
                    $dir = __DIR__ . "/new/new";
                    if (!is_dir($dir)) { mkdir($dir, 0777, true); }

                    // 6. SAVE PDF
                    $filename = "DL_" . preg_replace("/[^A-Za-z0-9]/", "", $dlno) . "_" . time() . ".pdf";
                    $fullPath = $dir . "/" . $filename;
                    $dbPath = "new/new/" . $filename; 

                    if (!file_put_contents($fullPath, $pdfContent)) {
                        $errorMsg = "Folder permission error.";
                    } else {

                        $newBal = $wallet - $fee;
                        mysqli_query($ahk_conn, "UPDATE members SET balance='$newBal' WHERE username='$username'");

                        $order_id = mt_rand(100000000000, 999999999999);
                        $app_no = $data['application_no'] ?? '';
                        $date = date("Y-m-d H:i:s");

                        // 7. INSERT INTO NEW dl_history TABLE
                        mysqli_query($ahk_conn, "
                            INSERT INTO dl_history (number, dob, tnsid, apiid, type, link, custno, amount, date_time)
                            VALUES ('$dlno', '$dob', '$order_id', '$app_no', 'dl', '$dbPath', '$username', '$fee', '$date')
                        ");

                        // 8. INSERT REPORT
                        mysqli_query($ahk_conn, "
                            INSERT INTO reports (user_id, site_id, parent_id, username, order_id, service, type, account_number, operator, name, amount, old_balance, new_balance, description, date_time, status) 
                            VALUES ('$user_id','$site_id','$parent_id','$username','$order_id','dl_gf_instant','Debit','$dlno','$usertype','$name','$fee','$wallet','$newBal','DL Download successful','$date','Success')
                        ");

                        $successMsg = $message;
                    }
                }
            } else { $errorMsg = $message; }
        }
        curl_close($ch);
    }
}
?>