<?php
ob_start();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

require_once('../titancore/titanconfig.php');
require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];
$u_name = $_SESSION['user_name'] ?? 'User';

$errorMsg = "";
$successMsg = "";
$alertPayload = null;

/* USER DATA */
$user = $conn->query("SELECT * FROM users WHERE id='$uid'")->fetch_assoc();

$wallet = floatval($user['wallet']);
$phone  = $user['phone'];

/* PRICE */
$priceRow = $conn->query("SELECT price FROM pricing WHERE service_name='aadhar_to_pan_req'");
$rate = ($priceRow && $priceRow->num_rows > 0)
    ? floatval($priceRow->fetch_assoc()['price'])
    : 80.00;

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

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

    if(strlen($aadharno) != 12){
        $errorMsg = "Invalid Aadhaar Number";
    }elseif($wallet < $rate){
        $errorMsg = "Insufficient Wallet Balance";
    }else{

        // Define internal API Key matching your setup
        $api_key = "2311e32848008d9eabd5fdb2db10b19e0614e81e5fd206743357469c6ec1ebd2";
        // Call your 3rd file's api gateway routing structure
        $api_url = "https://www.maxxapi.site/A2p?api_key=" . urlencode($api_key) . "&aadhaar_no=" . urlencode($aadharno);

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

        $res = curl_exec($ch);
        curl_close($ch);

        $responseData = json_decode($res, true);

        if (!$responseData || $responseData['status'] != "200") {
            $errorMsg = $responseData['message'] ?? "API Processing Error";
        } else {

            $pan  = $conn->real_escape_string($responseData['pan_no']);
            $app  = $conn->real_escape_string($responseData['application_no']);
            $date = date("Y-m-d H:i:s");

            $conn->begin_transaction();

            try{
                $new_balance = $wallet - $rate;

                // Update user wallet balance
                $conn->query("UPDATE users SET wallet='$new_balance' WHERE id='$uid'");

                // Insert directly into instant verification logs mapping to 1st script layout
                $stmt = $conn->prepare("
                    INSERT INTO aa2p
                    (aadharno, panno, status, username)
                    VALUES(?, ?, ?, ?)
                ");

                $status = 1; // Mark as Approved/Completed instantly
                $stmt->bind_param(
                    "ssis",
                    $aadharno,
                    $pan,
                    $status,
                    $phone
                );
                $stmt->execute();

                // Save to Wallet Logs
                $purpose = "Aadhaar To PAN";
                $conn->query("
                    INSERT INTO wallethistory
                    (userid, amount, balance, purpose, status, type)
                    VALUES
                    ('$phone', '$rate', '$new_balance', '$purpose', '1', 'Debit')
                ");

                $conn->commit();

                $wallet = $new_balance;
                $successMsg = "PAN Found Successfully";
                $alertPayload = [
                    'pan' => $pan,
                    'app' => $app
                ];

            }catch(Exception $e){
                $conn->rollback();
                $errorMsg = "Transaction Failed during ledger update.";
            }
        }
    }
}

/* HISTORY */
$history = $conn->query("
SELECT *
FROM aa2p
WHERE username='$phone'
ORDER BY id DESC
");
?>

<div class="row mb-3">
    <div class="col">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">

                    <div class="icon-item bg-primary-subtle shadow-none me-3">
                        <span class="fas fa-id-card text-primary fs-4"></span>
                    </div>

                    <div>
                        <h6 class="text-primary fs-10 mb-0">
                            Welcome, <?= htmlspecialchars($u_name); ?>
                        </h6>

                        <h4 class="text-primary fw-bold mb-0">
                            Aadhaar To PAN
                            <span class="text-info fw-medium">
                                Service
                            </span>
                        </h4>
                    </div>

                </div>

                <div class="col-md-auto">
                    <div class="form-control form-control-sm bg-white">
                        <b>Wallet Balance :
                            ₹<?= number_format($wallet,2); ?>
                        </b>
                    </div>
                </div>

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

<div class="row g-3">

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

        <div class="card shadow-sm border-0 border-top border-4 border-primary">

            <div class="card-header bg-light">
                <h5 class="mb-0 text-primary">
                    <i class="fas fa-search me-2"></i>
                    Aadhaar To PAN Request
                </h5>
            </div>

            <div class="card-body">

                <div class="alert alert-info">
                    <b>Charge:</b>
                    ₹<?= number_format($rate,2); ?>
                    <br>
                    PAN number will be fetched instantly.
                </div>

                <form method="POST">

                    <div class="mb-3">
                        <label class="form-label fw-bold">
                            Aadhaar Number
                        </label>
                        <input
                            type="text"
                            name="aadharno"
                            maxlength="12"
                            class="form-control text-center"
                            placeholder="Enter 12 Digit Aadhaar"
                            oninput="this.value=this.value.replace(/\D/g,'')"
                            required>
                    </div>

                    <button
                        type="submit"
                        name="submit_aadhar"
                        class="btn btn-primary w-100 fw-bold">
                        Submit Request (₹<?= number_format($rate,2); ?>)
                    </button>

                </form>

            </div>

        </div>

    </div>

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

        <div class="card shadow-sm border-0 border-top border-4 border-success">

            <div class="card-header bg-light">
                <h5 class="mb-0 text-success">
                    <i class="fas fa-history me-2"></i>
                    Aadhaar To PAN History
                </h5>
            </div>

            <div class="card-body">

                <div class="table-responsive">

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

                        <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th>Aadhaar</th>
                            <th>PAN</th>
                            <th>Status</th>
                        </tr>
                        </thead>

                        <tbody>

                        <?php if($history && $history->num_rows > 0): ?>

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

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

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

                                    <td>
                                        <span class="fw-bold text-dark"><?= !empty($row['panno']) ? htmlspecialchars($row['panno']) : 'N/A'; ?></span>
                                    </td>

                                    <td>
                                        <?php
                                        if($row['status']==0){
                                            echo '<span class="badge bg-warning text-dark">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>

</div>

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

<?php if($errorMsg): ?>
<script>
Swal.fire({
    icon: 'error',
    title: 'Error',
    text: '<?= addslashes($errorMsg); ?>'
});
</script>
<?php endif; ?>

<?php if($successMsg && $alertPayload): ?>
<script>
Swal.fire({
    icon: 'success',
    title: '<?= addslashes($successMsg); ?>',
    html: `<b>PAN Number:</b> <?= htmlspecialchars($alertPayload['pan']) ?><br>
           <b>Application No:</b> <?= htmlspecialchars($alertPayload['app']) ?><br>
           <small class="text-muted">Amount Debited: ₹<?= number_format($rate,2); ?></small>`
});
</script>
<?php endif; ?>

<?php
require_once('../titancore/TitanFooter.php');
ob_end_flush();
?>