<?php
session_start();
include('con.php');
include('header.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']);
$user_id = $udata['id'];
$name    = $udata['name'];

/* ================= SUBMIT FORM ================= */
if (isset($_POST['submit_data'])) {

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

    // Get service price
    $priceRow = mysqli_fetch_assoc(
        mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='dddhar'")
    );

    $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 {

        $ahk_conn->begin_transaction();

        try {

            $new_balance = $wallet - $fee;

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

            $stmt1->bind_param("ds", $new_balance, $username);
            $stmt1->execute();

            /* ===== INSERT DATA ===== */
            $stmt2 = $ahk_conn->prepare("
                INSERT INTO aaa2p
                (name, aadharno, username, status)
                VALUES (?, ?, ?, ?)
            ");

            $status = 0;

            $stmt2->bind_param(
                "sssi",
                $fullname,
                $aadharno,
                $username,
                $status
            );

            $stmt2->execute();

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

            $purpose = "Aadhar To PAN Find";
            $wstatus = 1;
            $type    = "Debit";

            $stmt3->bind_param(
                "sddsis",
                $username,
                $fee,
                $new_balance,
                $purpose,
                $wstatus,
                $type
            );

            $stmt3->execute();

            $ahk_conn->commit();

            $successMsg = "Data submitted successfully.";

        } catch (Exception $e) {

            $ahk_conn->rollback();
            $errorMsg = "Transaction failed.";

        }
    }
}

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

/* ================= RATE ================= */
$rateRow = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='dddhar'")
);

$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 p-4">

<h5 class="text-center text-primary">
Aadhaar To PAN Find
</h5>

<br>

<div class="text-center p-3 rounded mb-3"
style="background:#f8f9fa;border-left:4px solid #0d6efd;">

<strong class="text-primary">PAN Status:</strong><br>

<span class="text-muted">
Your PAN number will be updated within 24 hours.
</span>

</div>

<form method="POST">

<div class="mb-3">
<label>Full Name</label>

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

<div class="mb-3">
<label>Aadhaar Number</label>

<input type="text"
name="aadharno"
maxlength="12"
class="form-control"
required>
</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 p-3">

<h5 class="text-center text-primary">
PAN Find History
</h5>

<div class="table-responsive">

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

<thead class="table-dark">

<tr>
<th>ID</th>
<th>Name</th>
<th>Aadhaar</th>
<th>PAN</th>
<th>Status</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><?= $row['panno']; ?></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>

</tr>

<?php endwhile; ?>

<?php else: ?>

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

<?php endif; ?>

</tbody>

</table>

</div>
</div>
</div>

</div>
</div>

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

<?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>