<?php
session_start();

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

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

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

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

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

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

if (!$userQuery) {
    die("USER ERROR: " . mysqli_error($ahk_conn));
}

$udata = mysqli_fetch_assoc($userQuery);

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

/* ================= SUBMIT REQUEST ================= */

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

    $fullname = mysqli_real_escape_string(
        $ahk_conn,
        trim($_POST['fullname'])
    );

    $aadharno = preg_replace(
        '/[^0-9]/',
        '',
        $_POST['aadharno']
    );

    /* ================= PRICE ================= */

    $priceQuery = mysqli_query(
        $ahk_conn,
        "SELECT rate FROM price WHERE service='dddhar'"
    );

    if (!$priceQuery) {
        die("PRICE ERROR: " . mysqli_error($ahk_conn));
    }

    $priceRow = mysqli_fetch_assoc($priceQuery);

    $fee = $priceRow ? floatval($priceRow['rate']) : 0;

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

    if (empty($fullname)) {

        $errorMsg = "Please enter full name.";

    } elseif (strlen($aadharno) != 12) {

        $errorMsg = "Invalid Aadhaar Number.";

    } elseif ($wallet < $fee) {

        $errorMsg = "Insufficient Wallet Balance.";

    } else {

        /* ================= API URL ================= */

        $api_url =
            "https://www.maxxapi.site/aa2p?api_key=".$apikey.
            "&name=".urlencode($fullname).
            "&aadhar=".$aadharno;

        /* ================= CURL ================= */

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {

            die("CURL ERROR: " . curl_error($ch));

        } else {

            $result = json_decode($response, true);

            /*
            Example API Response:

            {
                "status":201,
                "message":"Request submitted successfully",
                "order_id":"AADH1779770194190"
            }
            */

            if (isset($result['order_id'])) {

                $order_id = $result['order_id'];

                /* ================= UPDATE WALLET ================= */

                $new_balance = $wallet - $fee;

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

                if (!$updateWallet) {

                    die(
                        "WALLET UPDATE ERROR: "
                        . mysqli_error($ahk_conn)
                    );
                }

                /* ================= INSERT DATA ================= */

                $insertQuery = mysqli_query(
                    $ahk_conn,
                    "INSERT INTO aaa2p
                    (
                        name,
                        aadharno,
                        username,
                        order_id,
                        panno,
                        status
                    )
                    VALUES
                    (
                        '$fullname',
                        '$aadharno',
                        '$username',
                        '$order_id',
                        '',
                        '0'
                    )"
                );

                if (!$insertQuery) {

                    die(
                        "INSERT ERROR: "
                        . mysqli_error($ahk_conn)
                    );
                }

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

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

                if (!$walletHistory) {

                    die(
                        "WALLET HISTORY ERROR: "
                        . mysqli_error($ahk_conn)
                    );
                }

                $wallet = $new_balance;

                $successMsg =
                    "Request submitted successfully.";

            } else {

                $errorMsg =
                    $result['message']
                    ?? "API Request Failed";
            }
        }

        curl_close($ch);
    }
}

/* ================= CHECK STATUS ================= */

if (isset($_GET['check_status'])) {

    $id = intval($_GET['check_status']);

    $checkQuery = mysqli_query(
        $ahk_conn,
        "SELECT * FROM aaa2p
         WHERE id='$id'
         AND username='$username'"
    );

    if (!$checkQuery) {

        die(
            "CHECK QUERY ERROR: "
            . mysqli_error($ahk_conn)
        );
    }

    $checkData = mysqli_fetch_assoc($checkQuery);

    if ($checkData) {

        $order_id = $checkData['order_id'];

        /* ================= CHECK API ================= */

        $check_url =
            "https://www.maxxapi.site/a2pcheck?order_id=".$order_id;

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $check_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $check_response = curl_exec($ch);

        if (curl_errno($ch)) {

            die("CURL ERROR: " . curl_error($ch));

        } else {

            $check_result = json_decode(
                $check_response,
                true
            );

            /*
            Possible Responses:

            {
                "message":"Pending"
            }

            {
                "message":"Successful"
            }

            {
                "panno":"ABCDE1234F"
            }
            */

            $message = strtolower(
                trim($check_result['message'] ?? '')
            );

            /* ================= APPROVED ================= */

            if (
                isset($check_result['panno']) &&
                !empty($check_result['panno'])
            ) {

                $panno = strtoupper(
                    trim($check_result['panno'])
                );

                $updatePan = mysqli_query(
                    $ahk_conn,
                    "UPDATE aaa2p
                     SET
                     panno='$panno',
                     status='1'
                     WHERE id='$id'"
                );

                if (!$updatePan) {

                    die(
                        "PAN UPDATE ERROR: "
                        . mysqli_error($ahk_conn)
                    );
                }

                $successMsg =
                    "PAN updated successfully.";
            }

            /* ================= PENDING ================= */

            elseif (
                $message == "pending"
                || $message == "successful"
                || $message == "processing"
            ) {

                mysqli_query(
                    $ahk_conn,
                    "UPDATE aaa2p
                     SET status='0'
                     WHERE id='$id'"
                );

                $successMsg =
                    "Request still pending.";
            }

            /* ================= REJECTED ================= */

            elseif (
                $message == "rejected"
                || $message == "failed"
            ) {

                mysqli_query(
                    $ahk_conn,
                    "UPDATE aaa2p
                     SET status='2'
                     WHERE id='$id'"
                );

                $errorMsg = "Request rejected.";
            }

            /* ================= NO STATUS CHANGE ================= */

            else {

                $successMsg =
                    $check_result['message']
                    ?? "Status checked successfully.";
            }
        }

        curl_close($ch);
    }
}

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

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

if (!$history) {
    die("HISTORY ERROR: " . mysqli_error($ahk_conn));
}

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

$rateQuery = mysqli_query(
    $ahk_conn,
    "SELECT rate FROM price WHERE service='dddhar'"
);

if (!$rateQuery) {
    die("RATE ERROR: " . mysqli_error($ahk_conn));
}

$rateRow = mysqli_fetch_assoc($rateQuery);

$rate = $rateRow ? floatval($rateRow['rate']) : 0;

?>

<!DOCTYPE html>
<html>

<head>

<title>Aadhaar To PAN Find</title>

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

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

</head>

<body class="bg-light">

<div class="container py-4">

<div class="row g-4">

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

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

<div class="card shadow border-0 rounded-4 p-4">

<h4 class="text-center text-primary mb-4">
Aadhaar To PAN Find
</h4>

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

<b>PAN Status Update</b><br>

Your PAN number will be updated within 24 hours.

</div>

<form method="POST">

<div class="mb-3">

<label class="fw-bold">
Full Name
</label>

<input type="text"
name="fullname"
class="form-control"
required>

</div>

<div class="mb-3">

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

<input type="text"
name="aadharno"
maxlength="12"
class="form-control"
required
oninput="this.value=this.value.replace(/[^0-9]/g,'')">

</div>

<button type="submit"
name="submit_data"
class="btn btn-success w-100">

Submit (₹<?= number_format($rate,2); ?>)

</button>

</form>

</div>

</div>

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

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

<div class="card shadow border-0 rounded-4 p-3">

<h4 class="text-center text-primary mb-3">
PAN Find History
</h4>

<div class="table-responsive">

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

<thead class="table-dark">

<tr>

<th>ID</th>
<th>Name</th>
<th>Aadhaar</th>
<th>PAN</th>
<th>Status</th>
<th>Action</th>

</tr>

</thead>

<tbody>

<?php if(mysqli_num_rows($history) > 0): ?>

<?php while($row = mysqli_fetch_assoc($history)): ?>

<tr>

<td><?= $row['id']; ?></td>

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

<td>
<?= substr($row['aadharno'],0,4)."XXXX".substr($row['aadharno'],8); ?>
</td>

<td>

<?php
if(!empty($row['panno'])){

    echo strtoupper($row['panno']);

}else{

    echo "-";
}
?>

</td>

<td>

<?php

if($row['status'] == 0){

    echo "<span class='badge bg-warning'>Pending</span>";

}elseif($row['status'] == 1){

    echo "<span class='badge bg-success'>Approved</span>";

}else{

    echo "<span class='badge bg-danger'>Rejected</span>";
}
?>

</td>

<td>

<?php if($row['status'] == 0): ?>

<a href="?check_status=<?= $row['id']; ?>"
class="btn btn-primary btn-sm">

Check Status

</a>

<?php else: ?>

--

<?php endif; ?>

</td>

</tr>

<?php endwhile; ?>

<?php else: ?>

<tr>

<td colspan="6">
No Records Found
</td>

</tr>

<?php endif; ?>

</tbody>

</table>

</div>

</div>

</div>

</div>

</div>

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

<?php if(!empty($successMsg)): ?>

<script>

Swal.fire({
    icon: 'success',
    title: 'Success',
    text: <?= json_encode($successMsg) ?>
});

</script>

<?php endif; ?>

<?php if(empty($successMsg) && !empty($errorMsg)): ?>

<script>

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

</script>

<?php endif; ?>

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

</body>
</html>