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

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

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

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

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

/* ================= FORM SUBMIT ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $vehno = strtoupper(preg_replace('/[^A-Z0-9]/', '', $_POST['vehno']));
    $type  = $_POST['type'];
    $amount = floatval($_POST['amount']);

    $source = "2 Wheeler";
    $status = 0;

    if (empty($vehno) || empty($type) || empty($amount)) {
        $errorMsg = "All fields are required.";
    } else {

        // Commission Calculation
        $min_commission = $amount * 0.15;
        $max_commission = $amount * 0.30;

        $insert = $ahk_conn->prepare("
            INSERT INTO form (username, vehno, type, source, status)
            VALUES (?, ?, ?, ?, ?)
        ");

        $insert->bind_param("ssssi", $username, $vehno, $type, $source,  $status);

        if ($insert->execute()) {
            header("Location: https://pbptwowheeler.policybazaar.com/?token=o5aMAq6qZ1tLXTODNpDyVbk4MP6pWDnq6hhpN5u%2BmyIqlNRZO27%2FmviFKrjEiHrP3saYIkdlxQbek23Cb73O9evFWLh2fWnZc5L36oeZ3V8MzKS3bu3bwTZqOXmxnfPxHjxuNnFuXxMrw2inJduE3WcRyDt9cVsFejUeQAh5VWtWZorj0nVhuIQC4wraCdqTfDGC7iBHGz4bIwLfVEGxEw%3D%3D&_gl=1*h8ti41*_ga*NjA2ODcyMTUwLjE3NzQwNzQ4NjM.*_ga_HJQ0E2N5FF*czE3NzY4Mjg3OTEkbzQkZzEkdDE3NzY4MzI1MTgkajU3JGwwJGgw");
            exit;
        } else {
            $errorMsg = "Insert failed.";
        }
    }
}

/* ================= FETCH DATA ================= */
$hist = $ahk_conn->prepare("SELECT * FROM form WHERE username=? ORDER BY id DESC");
$hist->bind_param("s", $username);
$hist->execute();
$formData = $hist->get_result();
?>

<!DOCTYPE html>
<html>
<head>
<title>2 Wheeler Insurance</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
.card-box {
    background:#fff;
    padding:25px;
    border-radius:16px;
    box-shadow:0 12px 30px rgba(0,0,0,0.08);
}
</style>
</head>

<body class="bg-light">

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

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

<h5 class="text-primary mb-3">2 Wheeler Insurance</h5>

<form method="POST">

<input type="text" name="vehno" required class="form-control mb-3 text-uppercase"
placeholder="PB10AB1234">

<select name="type" class="form-select mb-3" required>
<option value="">Select Policy Type</option>
<option value="Full">Full Insurance</option>
<option value="Third Party">Third Party</option>
</select>
    <label class="fw-bold"> To Check Estimated Commission:</label>

<input type="number" name="amount" id="amount" class="form-control mb-3"
placeholder="Enter Insurance Amount" required>

<div class="mb-3">
    <label class="fw-bold">Estimated Commission:</label>
    <div id="commissionBox" class="text-success fw-bold">₹0</div>
    <small id="commissionNote" class="text-muted"></small>
</div>

<button type="submit" class="btn btn-primary w-100">Proceed</button>

</form>

</div>
</div>

<!-- RIGHT SIDE -->
<div class="col-lg-8">

<div class="card-box mb-4">

<h5 class="text-success mb-3">Insurance Guidelines</h5>

<ul class="small text-muted">
<li>Insurance updates within <b>5–10 minutes</b></li>
<li>Commission: <b>Will Be Low For Seven  States of Northeast India </b></li>

<li>Commission: <b>20% – 25%</b></li>
<li>Full Insurance → Higher commission</li>
<li>Third Party → Lower commission</li>
<li>Payout within <b>24–48 hours</b></li>
</ul>

</div>

<!-- TABLE -->
<div class="card-box">

<h5 class="text-primary mb-3">Your Requests</h5>

<table class="table table-bordered text-center">
<thead class="table-dark">
<tr>
<th>Vehicle</th>
<th>Type</th>
<th>Amount</th>

<th>Status</th>
</tr>
</thead>

<tbody>

<?php if ($formData->num_rows > 0): ?>
<?php while ($row = $formData->fetch_assoc()): ?>
<tr>
<td><?= htmlspecialchars($row['vehno']) ?></td>
<td><?= $row['type'] ?></td>
<td>₹<?= $row['amount'] ?></td>

<td>
<?= $row['status']==0 ? '<span class="badge bg-warning">Pending</span>' : '<span class="badge bg-success">Done</span>' ?>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr><td colspan="5">No Data</td></tr>
<?php endif; ?>

</tbody>
</table>

</div>

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

<!-- JS CALCULATION -->
<script>
const amount = document.getElementById('amount');
const type = document.querySelector('[name="type"]');
const box = document.getElementById('commissionBox');
const note = document.getElementById('commissionNote');

function calc() {
    let amt = parseFloat(amount.value) || 0;
    let t = type.value;

    let min = amt * 0.15;
    let max = amt * 0.30;

    if (amt > 0) {
        box.innerHTML = "₹" + min.toFixed(2) + " - ₹" + max.toFixed(2);

        if (t === "Full") {
            note.innerHTML = "Full Insurance → High commission (25–30%)";
        } else if (t === "Third Party") {
            note.innerHTML = "Third Party → Lower commission";
        }
    } else {
        box.innerHTML = "₹0";
        note.innerHTML = "";
    }
}

amount.addEventListener('input', calc);
type.addEventListener('change', calc);
</script>

<?php if ($errorMsg): ?>
<script>alert("<?= $errorMsg ?>");</script>
<?php endif; ?>

</body>
</html>