<?php
session_start();
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

$username = $_SESSION['phone'];

/* ================= USER DATA ================= */

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

$wallet = (float)$udata['balance'];

/* ================= SERVICE RATE ================= */

$feeRow = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='pan_details_verify'")
);

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

$errorMsg = "";
$successData = null;

/* ================= VERIFY PAN ================= */

if (isset($_POST['verify_pan'])) {

    $pan_no = strtoupper(
        preg_replace('/[^A-Z0-9]/', '', $_POST['pan_no'])
    );

    /* ================= VALIDATION ================= */

    if (!preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]$/', $pan_no)) {

        $errorMsg = "Invalid PAN format.";

    } elseif ($wallet < $fee) {

        $errorMsg = "Insufficient wallet balance.";

    } else {

        /* ================= API CALL ================= */

        $api_key = "demo";

        $api_url = "https://www.maxxapi.site/Pan_details?api_key=".$api_key."&panno=".$pan_no;

        $ch = curl_init();

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

        $response = curl_exec($ch);

        curl_close($ch);

        $responseData = json_decode($response, true);

        /* ================= API RESPONSE ================= */

        if (!$responseData || $responseData['status'] != '200') {

            $errorMsg = $responseData['message'] ?? "No data found";

        } else {

            $name   = strtoupper($responseData['name'] ?? '');
            $father = strtoupper($responseData['father'] ?? '');
            $gender = strtoupper($responseData['gender'] ?? '');
            $dob    = $responseData['dob'] ?? '';
            $application_no = $responseData['application_no'] ?? '';

            $date = date("Y-m-d H:i:s");

            /* ================= WALLET DEDUCT ================= */

            $new_balance = $wallet - $fee;

            mysqli_query(
                $ahk_conn,
                "UPDATE users 
                 SET balance='$new_balance' 
                 WHERE phone='$username'"
            );

            /* ================= SAVE HISTORY ================= */

            mysqli_query(
                $ahk_conn,
                "INSERT INTO pan_verify_hkb
                (
                    name,
                    fathername,
                    gender,
                    dob,
                    pan,
                    username,
                    date
                )
                VALUES
                (
                    '$name',
                    '$father',
                    '$gender',
                    '$dob',
                    '$pan_no',
                    '$username',
                    '$date'
                )"
            );

            /* ================= WALLET HISTORY ================= */

            mysqli_query(
                $ahk_conn,
                "INSERT INTO wallethistory
                (
                    userid,
                    amount,
                    balance,
                    purpose,
                    status,
                    type
                )
                VALUES
                (
                    '$username',
                    '$fee',
                    '$new_balance',
                    'PAN Verification',
                    '1',
                    'Debit'
                )"
            );

            /* ================= SUCCESS DATA ================= */

            $successData = [
                "status" => "200",
                "pan_no" => $pan_no,
                "name" => $name,
                "father" => $father,
                "dob" => $dob,
                "gender" => $gender,
                "application_no" => $application_no
            ];

            /* ================= JSON API RESPONSE ================= */

            if (isset($_POST['api'])) {

                header('Content-Type: application/json');

                echo json_encode($successData);

                exit;
            }
        }
    }
}

/* ================= HISTORY ================= */

$history = mysqli_query(
    $ahk_conn,
    "SELECT * FROM pan_verify_hkb 
     WHERE username='$username' 
     ORDER BY id DESC"
);
?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>PAN Verification</title>

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

<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">

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

<style>

body{
    background:#f4f7fb;
}

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

.verify-btn{
    height:48px;
    border-radius:10px;
    font-weight:600;
}

.table th{
    white-space:nowrap;
}

</style>

</head>

<body>

<div class="container py-4">

<div class="row g-4">

<!-- ================= FORM ================= -->

<div class="col-lg-4">

<div class="card-box">

<h4 class="text-center text-primary mb-4">
PAN Verification
</h4>

<form method="POST">

<input
type="text"
name="pan_no"
maxlength="10"
required
class="form-control text-center mb-3"
placeholder="ABCDE1234F"
oninput="this.value=this.value.toUpperCase().replace(/[^A-Z0-9]/g,'')"
>

<div class="alert alert-warning text-center">

Verification Fee :
<b>₹<?= number_format($fee,2) ?></b>

</div>

<button
type="submit"
name="verify_pan"
class="btn btn-primary w-100 verify-btn"
>

Verify PAN

</button>

</form>

</div>

</div>

<!-- ================= HISTORY ================= -->

<div class="col-lg-8">

<div class="card-box">

<h5 class="mb-3">
Verification History
</h5>

<div class="table-responsive">

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

<thead class="table-dark">

<tr>
<th>ID</th>
<th>Date</th>
<th>PAN</th>
<th>Name</th>
<th>Father</th>
<th>DOB</th>
<th>Gender</th>
<th>Slip</th>
</tr>

</thead>

<tbody>

<?php while ($r = mysqli_fetch_assoc($history)) { ?>

<tr>

<td>#<?= $r['id'] ?></td>

<td>
<?= date('d M Y h:i A', strtotime($r['date'])) ?>
</td>

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

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

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

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

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

<td>

<button
class="btn btn-sm btn-info"
onclick='viewSlip(<?= json_encode($r) ?>)'
>

View

</button>

</td>

</tr>

<?php } ?>

</tbody>

</table>

</div>

</div>

</div>

</div>

</div>

<!-- ================= ERROR ALERT ================= -->

<?php if ($errorMsg) { ?>

<script>

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

</script>

<?php } ?>

<!-- ================= SUCCESS ALERT ================= -->

<?php if ($successData) { ?>

<script>

Swal.fire({

    icon:'success',

    title:'PAN Verified Successfully',

    html:`

    <div style="text-align:left">

    <p><b>PAN No :</b> <?= $successData['pan_no'] ?></p>

    <p><b>Name :</b> <?= $successData['name'] ?></p>

    <p><b>Father :</b> <?= $successData['father'] ?></p>

    <p><b>DOB :</b> <?= $successData['dob'] ?></p>

    <p><b>Gender :</b> <?= $successData['gender'] ?></p>

    <p><b>Application No :</b> <?= $successData['application_no'] ?></p>

    </div>

    `

});

</script>

<?php } ?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

<script>

$('#panTable').DataTable();

function viewSlip(d){

    Swal.fire({

        title:'PAN Verification Slip',

        html:`

        <div style="text-align:left">

        <p><b>PAN :</b> ${d.pan}</p>

        <p><b>Name :</b> ${d.name}</p>

        <p><b>Father :</b> ${d.fathername}</p>

        <p><b>DOB :</b> ${d.dob}</p>

        <p><b>Gender :</b> ${d.gender}</p>

        <p><b>Date :</b> ${d.date}</p>

        </div>

        `,

        showCancelButton:true,
        confirmButtonText:'Print'

    }).then((result)=>{

        if(result.isConfirmed){

            window.print();

        }

    });

}

</script>

</body>
</html>