<?php
session_start();
include('con.php');
include('header.php');

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

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

/* ================= USER DATA ================= */
$stmt = $ahk_conn->prepare("SELECT * FROM users WHERE id=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$udata = $stmt->get_result()->fetch_assoc();

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

/* ================= AADHAAR SUBMIT ================= */
if (isset($_POST['submit_aadhar'])) {

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

    // Get price
    $priceRow = mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT rate FROM price WHERE service='ddhar'"));
    $fee = $priceRow ? floatval($priceRow['rate']) : 0;

    // Validate Aadhaar
    if (strlen($aadharno) != 12) {
        $errorMsg = "Invalid Aadhaar number.";
    } elseif ($wallet < $fee) {
        $errorMsg = "Insufficient wallet balance.";
    } else {

        $ahk_conn->begin_transaction();

        try {

            $new_balance = $wallet - $fee;

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

            /* ===== INSERT AADHAAR ===== */
            $stmt2 = $ahk_conn->prepare("
                INSERT INTO aa2p (aadharno, status,username) 
                VALUES (?, ?,?)
            ");
            $stmt2->bind_param("sis", $aadharno, $status,$username);
            $stmt2->execute();

            /* ===== WALLET HISTORY ===== */
            mysqli_query($ahk_conn,"
                INSERT INTO wallethistory
                (userid, amount, balance, purpose, status, type)
                VALUES
                ('$username', '$fee', '$new_balance', 'Aadhar 2 Pan 2.0', '1', 'Debit')
            ");

            $ahk_conn->commit();

            $successMsg = "Aadhaar submitted successfully.";

        } catch (Exception $e) {
            $ahk_conn->rollback();
            $errorMsg = "Transaction failed!";
        }
    }
}

/* ================= HISTORY ================= */
$history = mysqli_query($ahk_conn, "SELECT * FROM aa2p where username=$username ORDER BY id DESC");
// Show rate
$rate = floatval(mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT rate FROM price WHERE service='ddhar'"))['rate']);
?>

<!DOCTYPE html>
<html>
<head>
<title>Aadhaar Entry</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 No. To Pan Find</h5><br>

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

<button type="submit" name="submit_aadhar" 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>

<table class="table table-bordered text-center">
<thead class="table-dark">
<tr>
<th>ID</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><?= 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="4">No Records Found</td></tr>

<?php endif; ?>

</tbody>
</table>

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