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

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

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

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

/* ================= USER DATA ================= */
$udata = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'"));
$wallet = (float)$udata['balance'];
$parent = $udata['parent']; // Parent/Agent phone for commission

/* ================= SERVICE RATE ================= */
$feeRow = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='mobile_to_pan'")
);
$fee = (float)($feeRow['rate'] ?? 0);

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

    $mobile = trim($_POST['mobile']);

    if (!preg_match('/^[6-9]\d{9}$/', $mobile)) {
        $errorMsg = "Invalid mobile number.";
    }
    elseif ($wallet < $fee) {
        $errorMsg = "Insufficient wallet balance.";
    }
    else {

        $api_key = "TNG-API-1731b6-001c9e-0c12ce-bb1787-8288bf";
        $api_url = "https://secure.thenextgenapi.co.in/api/mobile-to-pan/v1/mobile-to-pan-verification"
                 . "?apikey=$api_key&mobileNumber=$mobile";

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

        $data = json_decode($response, true);

        if (!$data) {
            $errorMsg = "Invalid API response.";
        }
        elseif (($data['sampleCode'] ?? 0) != 200) {
            $errorMsg = $data['message'] ?? $data['Message'] ?? "API failed.";
        }
        elseif (empty($data['data']['pan_number'])) {
            $errorMsg = "PAN not found.";
        }
        else {

            $pan = mysqli_real_escape_string($ahk_conn, $data['data']['pan_number']);
            $app = mysqli_real_escape_string($ahk_conn, $data['application_no']);
            $mobile_safe = mysqli_real_escape_string($ahk_conn, $mobile);
            $date = date("Y-m-d H:i:s");

            /* ===== WALLET DEDUCT ===== */
            $new_balance = $wallet - $fee;
            mysqli_query($ahk_conn, "UPDATE users SET balance='$new_balance' WHERE phone='$username'");

            /* ===== SAVE HISTORY ===== */
            mysqli_query($ahk_conn, "
                INSERT INTO mobile_to_pan
                (mobile, pan, application_no, username, date)
                VALUES
                ('$mobile_safe', '$pan', '$app', '$username', '$date')
            ");

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

            /* ===== PARENT/AGENT COMMISSION 15% ===== */
            if (!empty($parent) && strtolower($parent) !== 'admin') {
                $commission = round($fee * 0.15, 2); // 15% commission
                if ($commission > 0) {
                    $pRes = mysqli_query($ahk_conn, "SELECT balance FROM users WHERE phone='$parent' LIMIT 1");
                    if (mysqli_num_rows($pRes) > 0) {
                        $pData = mysqli_fetch_assoc($pRes);
                        $parent_balance = (float)$pData['balance'];
                        $parent_newbalance = $parent_balance + $commission;

                        // Update parent balance
                        mysqli_query($ahk_conn, "UPDATE users SET balance='$parent_newbalance' WHERE phone='$parent'");

                        // Log in wallet history
                        mysqli_query($ahk_conn, "
                            INSERT INTO wallethistory
                            (userid, amount, balance, purpose, status, type)
                            VALUES
                            ('$parent', '$commission', '$parent_newbalance', 'Commission from $username', 1, 'Credit')
                        ");
                    }
                }
            }

            $successMsg = "PAN Found Successfully";
        }
    }
}

/* ================= HISTORY + 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 = mysqli_query($ahk_conn, "
    SELECT * FROM mobile_to_pan
    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-box{
    background:#fff;
    padding:25px;
    border-radius:15px;
    box-shadow:0 8px 25px rgba(0,0,0,.1)
}
.pan-badge{
    background:#e3f2fd;
    color:#0d47a1;
    padding:4px 8px;
    border-radius:5px;
    font-weight:bold
}
</style>
</head>

<body class="bg-light">

<div class="container-fluid px-4 py-4">
<div class="row g-4">

<!-- FORM -->
<div class="col-lg-4">
<div class="card-box">

<h5 class="text-primary mb-3">📱 Find PAN via Mobile</h5>

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

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

<button class="btn btn-primary w-100" name="find_pan">
Search PAN
</button>

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

<!-- HISTORY -->
<div class="col-lg-8">
<div class="card-box">

<form method="POST" class="input-group mb-3">
<input type="text" name="search_val" class="form-control" placeholder="Search Mobile / PAN">
<button class="btn btn-primary">Search</button>
</form>

<table class="table table-bordered text-center align-middle">
<thead class="table-dark">
<tr>
<th>ID</th>
<th>Mobile</th>
<th>PAN</th>
<th>Application</th>
<th>Date</th>
</tr>
</thead>
<tbody>

<?php if (mysqli_num_rows($history)): ?>
<?php while ($r = mysqli_fetch_assoc($history)): ?>
<tr>
<td>#<?= $r['id'] ?></td>
<td><?= $r['mobile'] ?></td>
<td><span class="pan-badge"><?= $r['pan'] ?></span></td>
<td><?= $r['application_no'] ?></td>
<td><?= date('d M Y h:i A', strtotime($r['date'])) ?></td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td colspan="5">No Records Found</td>
</tr>
<?php endif; ?>

</tbody>
</table>

</div>
</div>

</div>
</div>

<!-- ALERTS -->
<?php if ($errorMsg): ?>
<script>
Swal.fire({
    icon: 'error',
    title: 'Failed',
    text: <?= json_encode($errorMsg) ?>
});
</script>
<?php endif; ?>

<?php if ($successMsg && isset($data)): ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'PAN Found',
    html: `<b>PAN:</b> <?= $data['data']['pan_number'] ?><br>
           <b>Application:</b> <?= $data['application_no'] ?><br>
           <small>₹<?= number_format($fee,2) ?> debited</small>`
});
</script>
<?php endif; ?>

<?php include('footer.php'); ?>
</body>
</html>
