<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

session_start();

include('con.php');
include('header.php');

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

$username = $_SESSION['phone'];

$errorMsg = null;
$successMsg = null;
$redirectAfterSuccess = false;

/* ================= USER DATA ================= */
$udata = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'")
);

$wallet    = floatval($udata['balance']);
$user_id   = $udata['id'];
$usertype  = $udata['type'];
$name_user = $udata['name'];
$parent    = $udata['parent'];

/* ================= SERVICE FEE ================= */
$feeRow = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='farmer_pdf'")
);

$fee = (float)($feeRow['rate'] ?? 10);

/* ================= FARMER PDF DOWNLOAD ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $aadhar = preg_replace('/[^0-9]/', '', $_POST['aadhar'] ?? '');
    $state  = strtoupper(trim($_POST['state'] ?? ''));

    /* ================= VALIDATION ================= */
    if (strlen($aadhar) != 12) {

        $errorMsg = "Invalid Aadhaar Number.";

    } elseif (empty($state)) {

        $errorMsg = "State is required.";

    } elseif ($wallet < $fee) {

        $errorMsg = "Insufficient wallet balance.";

    } else {

        /* ================= API CALL ================= */
        $api_url = "https://www.maxxapi.site/farmer?api_key=demo&aadhar=".$aadhar."&state=".$state;

        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL            => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 60,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false
        ]);

        $res = curl_exec($ch);

        if (curl_errno($ch)) {

            $errorMsg = curl_error($ch);

        } else {

            curl_close($ch);

            $data = json_decode($res, true);

            /* ================= INVALID RESPONSE ================= */
            if (!$data || !isset($data['status'])) {

                $errorMsg = "Invalid API response.";

            }

            /* ================= FAILED RESPONSE ================= */
            elseif ($data['status'] != "200") {

                $errorMsg = $data['message'] ?? "Farmer PDF not found.";

            }

            /* ================= PDF CHECK ================= */
            elseif (empty($data['pdf_base64'])) {

                $errorMsg = "PDF data missing.";

            }

            else {

                $fullname = strtoupper($data['fullname'] ?? '');

                $pdf = $data['pdf_base64'];

                /* ================= REMOVE PREFIX ================= */
                if (strpos($pdf, ',') !== false) {
                    $pdf = explode(',', $pdf, 2)[1];
                }

                /* ================= BASE64 DECODE ================= */
                $content = base64_decode($pdf, true);

                if ($content === false) {

                    $errorMsg = "PDF decode failed.";

                } else {

                    /* ================= CREATE FOLDER ================= */
                    $dir = "uploads/farmer_pdf";

                    if (!is_dir($dir)) {
                        mkdir($dir, 0755, true);
                    }

                    /* ================= FILE NAME ================= */
                    $file = "FARMER_" . $aadhar . "_" . time() . ".pdf";

                    /* ================= SAVE FILE ================= */
                    if (!file_put_contents("$dir/$file", $content)) {

                        $errorMsg = "Unable to save PDF.";

                    } else {

                        /* ================= BALANCE UPDATE ================= */
                        $newBal   = $wallet - $fee;
                        $order_id = mt_rand(100000000000, 999999999999);

                        /* ================= UPDATE WALLET ================= */
                        $up = $ahk_conn->prepare("
                            UPDATE users 
                            SET balance=? 
                            WHERE phone=?
                        ");

                        $up->bind_param("ds", $newBal, $username);
                        $up->execute();

                        /* ================= PDF PATH ================= */
                        $path = "$dir/$file";

                        /* ================= HISTORY INSERT ================= */
                        $his = $ahk_conn->prepare("
                            INSERT INTO farmerhis
                            (number, tnsid, apiid, type, link, custno)
                            VALUES (?, ?, ?, 'farmer_pdf', ?, ?)
                        ");

                        $apiid = $aadhar;

                        $his->bind_param(
                            "sssss",
                            $aadhar,
                            $order_id,
                            $apiid,
                            $path,
                            $username
                        );

                        $his->execute();

                        /* ================= WALLET HISTORY ================= */
                        $wallethist = $ahk_conn->prepare("
                            INSERT INTO wallethistory
                            (
                                userid,
                                amount,
                                balance,
                                purpose,
                                status,
                                type
                            )
                            VALUES (?, ?, ?, ?, ?, ?)
                        ");

                        $status  = 1;
                        $type    = 'Debit';
                        $purpose = 'Farmer PDF';

                        $wallethist->bind_param(
                            "sddsis",
                            $username,
                            $fee,
                            $newBal,
                            $purpose,
                            $status,
                            $type
                        );

                        $wallethist->execute();

                        /* ================= PARENT COMMISSION ================= */
                        if (!empty($parent) && strtolower($parent) !== 'admin') {

                            $commission = round($fee * 0.10, 2);

                            if ($commission > 0) {

                                $pRes = mysqli_query(
                                    $ahk_conn,
                                    "SELECT balance 
                                     FROM users 
                                     WHERE phone='$parent' 
                                     LIMIT 1"
                                );

                                if (mysqli_num_rows($pRes) > 0) {

                                    $pData = mysqli_fetch_assoc($pRes);

                                    $parent_balance = (float)$pData['balance'];

                                    $parent_newbalance = $parent_balance + $commission;

                                    /* ===== UPDATE PARENT BALANCE ===== */
                                    mysqli_query(
                                        $ahk_conn,
                                        "UPDATE users 
                                         SET balance='$parent_newbalance' 
                                         WHERE phone='$parent'"
                                    );

                                    /* ===== INSERT PARENT WALLET HISTORY ===== */
                                    mysqli_query($ahk_conn, "
                                        INSERT INTO wallethistory
                                        (
                                            userid,
                                            amount,
                                            balance,
                                            purpose,
                                            status,
                                            type
                                        )
                                        VALUES
                                        (
                                            '$parent',
                                            '$commission',
                                            '$parent_newbalance',
                                            'Commission from $username',
                                            1,
                                            'Credit'
                                        )
                                    ");
                                }
                            }
                        }

                        /* ================= SUCCESS ================= */
                        $successMsg = "Farmer PDF generated successfully.";

                        $redirectAfterSuccess = true;
                    }
                }
            }
        }
    }
}

/* ================= HISTORY ================= */
$hist = $ahk_conn->prepare("
    SELECT * FROM farmerhis
    WHERE custno=? AND type='farmer_pdf'
    ORDER BY id DESC
");

$hist->bind_param("s", $username);

$hist->execute();

$history = $hist->get_result();

?>

<!DOCTYPE html>
<html>
<head>

<title>Farmer PDF Download</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>

.card-box{
    background:#fff;
    padding:25px;
    border-radius:15px;
    box-shadow:0 8px 25px rgba(0,0,0,.1)
}

</style>

</head>

<body class="bg-light">

<div class="container-fluid px-4 py-4">

<div class="row g-4">

<!-- LEFT FORM -->
<div class="col-lg-4">

<div class="card-box">

<h5 class="text-primary mb-3">
Farmer PDF Download
</h5>

<form method="POST" id="farmerForm">

<label class="fw-bold mb-1">
Aadhaar Number
</label>

<input
type="text"
name="aadhar"
required
maxlength="12"
class="form-control mb-3"
placeholder="Enter Aadhaar Number"
oninput="this.value=this.value.replace(/[^0-9]/g,'')"
>

<label class="fw-bold mb-1">
State
</label>

<select name="state" class="form-select mb-3" required>
<option value="">Select State</option>
<option value="UP">UP</option>
<option value="BIHAR">BIHAR</option>
<option value="MP">MP</option>
<option value="RJ">RJ</option>
<option value="HR">HR</option>
<option value="PB">PB</option>
</select>

<div class="alert alert-warning text-center py-1">
Fee: ₹<?= number_format($fee,2) ?>
</div>

<button type="submit" id="submitBtn" class="btn btn-primary w-100">
Generate Farmer PDF
</button>

</form>

</div>

</div>

<!-- RIGHT HISTORY -->
<div class="col-lg-8">

<div class="card-box">

<table class="table table-bordered text-center align-middle">

<thead class="table-dark">

<tr>
<th>Aadhaar</th>
<th>Txn ID</th>
<th>Download</th>
</tr>

</thead>

<tbody>

<?php if ($history->num_rows): ?>

<?php while ($r = $history->fetch_assoc()): ?>

<tr>

<td class="fw-bold">
<?= htmlspecialchars($r['number']) ?>
</td>

<td>
<?= htmlspecialchars($r['tnsid']) ?>
</td>

<td>

<a
target="_blank"
class="btn btn-success btn-sm"
href="dow.php?file=<?= urlencode($r['link']) ?>"
>
Open PDF
</a>

</td>

</tr>

<?php endwhile; ?>

<?php else: ?>

<tr>

<td colspan="3" class="text-muted">
No Farmer PDF History
</td>

</tr>

<?php endif; ?>

</tbody>

</table>

</div>

</div>

</div>

</div>

<?php if ($errorMsg): ?>

<script>

Swal.fire({
    icon: 'error',
    title: 'Error',
    text: <?= json_encode($errorMsg) ?>
});

</script>

<?php endif; ?>

<?php if ($redirectAfterSuccess): ?>

<script>

Swal.fire({
    icon: 'success',
    title: 'Success',
    text: <?= json_encode($successMsg) ?>,
    confirmButtonText: 'Continue'
}).then(() => {
    window.location.href = "farmer_pdf.php";
});

</script>

<?php endif; ?>

<script>

document.getElementById("farmerForm").addEventListener("submit", function () {

    const btn = document.getElementById("submitBtn");

    btn.disabled = true;

    btn.innerHTML = "Processing...";

});

</script>

<?php include('footer.php'); ?>

</body>
</html>