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

session_start();

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 ================= */

$stmt = $ahk_conn->prepare("SELECT * FROM users WHERE phone=?");
$stmt->bind_param("s", $username);
$stmt->execute();

$udata = $stmt->get_result()->fetch_assoc();

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

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

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

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

/* ================= FORM SUBMIT ================= */

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

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

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

    if ($cust_name == "" || !preg_match('/^[0-9]{10}$/', $mobile)) {

        $errorMsg = "Enter valid Name & Mobile Number.";

    } elseif ($wallet < $fee) {

        $errorMsg = "Insufficient Wallet Balance!";

    } else {

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

        $api_url = "https://maxxapi.site/mm2p?api_key=".$apikey."&name=".urlencode($cust_name)."&mobile=".$mobile;

        $ch = curl_init();

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

        $res = curl_exec($ch);

        if (curl_errno($ch)) {

            $errorMsg = curl_error($ch);

        } else {

            $responseData = json_decode($res, true);

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

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

                $errorMsg = $responseData['message'] ?? "Verification Failed.";

            } else {

                try {

                    $ahk_conn->begin_transaction();

                    $pan  = strtoupper($responseData['pan_no']);
                    $rname = $responseData['name'];
                    $rmobile = $responseData['mobile'];

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

                    $old_balance = $wallet;
                    $new_balance = $wallet - $fee;

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

                    $update = $ahk_conn->prepare("UPDATE users SET balance=? WHERE phone=?");
                    $update->bind_param("ds", $new_balance, $username);
                    $update->execute();

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

                    $hist = $ahk_conn->prepare("
                        INSERT INTO mobile_pan_history
                        (name, mobile, pan, username, date)
                        VALUES (?, ?, ?, ?, ?)
                    ");

                    $hist->bind_param(
                        "sssss",
                        $rname,
                        $rmobile,
                        $pan,
                        $username,
                        $date
                    );

                    $hist->execute();

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

                    $purpose = "Mobile to PAN";
                    $status  = 1;
                    $type    = "Debit";

                    $walletHistory = $ahk_conn->prepare("
                        INSERT INTO wallethistory
                        (userid, amount, oldbalance, new_balance, purpose, status, type, date)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                    $walletHistory->bind_param(
                        "sdddssss",
                        $username,
                        $fee,
                        $old_balance,
                        $new_balance,
                        $purpose,
                        $status,
                        $type,
                        $date
                    );

                    $walletHistory->execute();

                    $ahk_conn->commit();

                    $successMsg = "PAN Found : ".$pan;

                    // refresh wallet
                    $wallet = $new_balance;

                } catch (Exception $e) {

                    $ahk_conn->rollback();

                    $errorMsg = "Transaction Failed!";
                }
            }
        }

        curl_close($ch);
    }
}

/* ================= SEARCH ================= */

$search = "";

if (!empty($_POST['search_val'])) {

    $s = mysqli_real_escape_string($ahk_conn, $_POST['search_val']);

    $search = " AND (mobile LIKE '%$s%' OR pan LIKE '%$s%')";
}

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

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

?>

<!DOCTYPE html>
<html>

<head>

<title>Mobile to PAN</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{
    border-radius:12px;
}

h5{
    font-weight:600;
}

.table th{
    background:#f1f1f1;
}

.balance-box{
    font-size:18px;
    font-weight:bold;
    color:green;
}

</style>

</head>

<body class="bg-light">

<div class="container py-4">

<div class="row g-3">

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

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

<div class="card p-3 shadow-sm">

<h5 class="mb-3">🔍 Find PAN via Mobile</h5>

<div class="balance-box text-center mb-3">
Wallet : ₹<?= number_format($wallet,2) ?>
</div>

<form method="POST">

<input
type="text"
name="cust_name"
required
class="form-control mb-2"
placeholder="Enter Full Name">

<input
type="text"
name="mobile"
maxlength="10"
required
class="form-control mb-2 text-center"
placeholder="Enter Mobile Number"
oninput="this.value=this.value.replace(/\D/g,'')">

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

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

Search PAN

</button>

</form>

</div>

</div>

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

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

<div class="card p-3 shadow-sm">

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

<form method="POST" class="d-flex mb-3">

<input
type="text"
name="search_val"
class="form-control me-2"
placeholder="Search Mobile / PAN">

<button class="btn btn-primary">
Search
</button>

</form>

<div class="table-responsive">

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

<tr>
<th>ID</th>
<th>Name</th>
<th>Mobile</th>
<th>PAN</th>
<th>Date</th>
</tr>

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

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

<tr>

<td><?= $r['id'] ?></td>
<td><?= $r['name'] ?></td>
<td><?= $r['mobile'] ?></td>
<td><?= $r['pan'] ?></td>
<td><?= $r['date'] ?></td>

</tr>

<?php endwhile; ?>

<?php else: ?>

<tr>
<td colspan="5">No Records Found</td>
</tr>

<?php endif; ?>

</table>

</div>

</div>

</div>

</div>

</div>

<!-- ================= ALERTS ================= -->

<?php if($errorMsg): ?>

<script>
Swal.fire(
    'Error',
    '<?= $errorMsg ?>',
    'error'
);
</script>

<?php endif; ?>

<?php if($successMsg): ?>

<script>
Swal.fire(
    'Success',
    '<?= $successMsg ?>',
    'success'
);
</script>

<?php endif; ?>

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

</body>
</html>