<?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 = "";

/* ================= USER DATA ================= */
$user = $conn->query("SELECT * FROM users WHERE id='$uid'")->fetch_assoc();
$wallet = floatval($user['wallet'] ?? $user['balance'] ?? 0);
$phone  = $user['phone'];

/* ================= FETCH LL EXAM RATE ================= */
$priceRow = $conn->query("SELECT price FROM pricing WHERE service_name='ll'");
$fee = ($priceRow && $priceRow->num_rows > 0) 
    ? floatval($priceRow->fetch_assoc()['price']) 
    : 50.00; // Customizable standard architecture fallback amount

/* ================= FORM SUBMISSION ================= */
if (isset($_POST['submit_ll'])) {

    $application_no = trim($_POST['application_no']);
    $password       = trim($_POST['password'] ?? '');
    $dob            = trim($_POST['dob']);
    $state          = trim($_POST['state']);
    $date           = date("Y-m-d H:i:s");
    $order_id       = mt_rand(100000000000, 999999999999);

    if ($wallet < $fee) {
        $errorMsg = "Insufficient wallet balance.";
    } else {
        
        $safe_app   = $conn->real_escape_string($application_no);
        $safe_pass  = $conn->real_escape_string($password);
        $safe_dob   = $conn->real_escape_string($dob);
        $safe_state = $conn->real_escape_string($state);
        
        $conn->begin_transaction();

        try {
            $new_balance = $wallet - $fee;
            
            // Deduct system wallet balance dynamically
            $balance_field = isset($user['wallet']) ? 'wallet' : 'balance';
            $conn->query("UPDATE users SET $balance_field='$new_balance' WHERE id='$uid'");

            /* ===== INSERT MAIN REQUESTS ===== */
            $conn->query("
                INSERT INTO ll_exam_requests 
                (application_no, password, dob, state, username, date) 
                VALUES 
                ('$safe_app', '$safe_pass', '$safe_dob', '$safe_state', '$phone', '$date')
            ");

            /* ===== INSERT LOG HISTORY ===== */
            $conn->query("
                INSERT INTO ll_exam_history 
                (order_id, application_no, dob, state, username, status, date, password) 
                VALUES 
                ('$order_id', '$safe_app', '$safe_dob', '$safe_state', '$phone', '0', '$date', '$safe_pass')
            ");

            /* ===== INSERT WALLET LEDGER ===== */
            $conn->query("
                INSERT INTO wallethistory 
                (userid, amount, balance, purpose, status, type) 
                VALUES 
                ('$phone', '$fee', '$new_balance', 'LL Exam 2.0', '1', 'Debit')
            ");

            $conn->commit();

            /* ===== NOTIFICATION GATEWAY ===== */
            $sms_message = urlencode("New LL Exam Request | App No: $application_no | DOB: $dob | State: $state | User: $phone");
            $sms_url = "https://sms.liveone.tech/send-message?api_key=5BStKiAVs0Bb9vddDJR9u8rieXXUVU&sender=917973553513&number=919803416023&message=$sms_message";

            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $sms_url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 5
            ]);
            curl_exec($ch);
            curl_close($ch);

            $wallet = $new_balance;
            $successMsg = "LL Exam details submitted successfully.";

        } catch (Exception $e) {
            $conn->rollback();
            $errorMsg = "Transaction failed. Please try again.";
        }
    }
}

/* ================= HISTORY RECORDS ================= */
$history = $conn->query("SELECT * FROM ll_exam_history 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-graduation-cap 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">Learner License (LL) <span class="text-info fw-medium">Exam Pass Module</span></h4>
                    </div>
                </div>
                <div class="col-md-auto text-end">
                    <div class="form-control form-control-sm bg-white fw-bold">
                        Wallet Balance: ₹<?= number_format($wallet, 2); ?>
                    </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-file-alt me-2"></i>Submit LL Exam Details
                </h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Application Number</label>
                        <input type="text" name="application_no" required class="form-control font-monospace" placeholder="Enter Application Number">
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Password <span class="text-muted small fw-normal">(Optional)</span></label>
                        <input type="text" name="password" class="form-control" placeholder="Enter Portal Password">
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Date of Birth</label>
                        <input type="date" name="dob" required class="form-control">
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">State Jurisdiction</label>
                        <select name="state" required class="form-select">
                            <option value="">Select State</option>
                            <option value="Punjab">Punjab</option>
                            <option value="Haryana">Haryana</option>
                            <option value="Delhi">Delhi</option>
                            <option value="Rajasthan">Rajasthan</option>
                            <option value="Uttar Pradesh">Uttar Pradesh</option>
                            <option value="Other">Other State</option>
                        </select>
                    </div>

                    <button type="submit" name="submit_ll" class="btn btn-primary w-100 fw-bold mt-2">
                        Process Submission (₹<?= number_format($fee, 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>LL Exam Submission 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>Order ID</th>
                                <th>Application Details</th>
                                <th>DOB</th>
                                <th>State</th>
                                <th>Status</th>
                                <th>Verification Output</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($history && $history->num_rows > 0): ?>
                                <?php while($row = $history->fetch_assoc()): ?>
                                    <tr>
                                        <td><small class="fw-semibold text-secondary font-monospace">#<?= $row['order_id'] ?: $row['id']; ?></small></td>
                                        <td>
                                            <div class="fw-bold text-dark font-monospace"><?= htmlspecialchars($row['application_no']); ?></div>
                                            <?php if(!empty($row['password'])): ?>
                                                <small class="text-muted">Pass: <?= htmlspecialchars($row['password']); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td><span class="badge bg-light text-dark border px-2 font-monospace"><?= htmlspecialchars($row['dob']); ?></span></td>
                                        <td><small class="fw-bold"><?= htmlspecialchars($row['state']); ?></small></td>
                                        <td>
                                            <?php
                                            if ($row['status'] == 0) {
                                                echo '<span class="badge bg-warning text-dark"><i class="fas fa-clock fa-spin me-1"></i>Pending</span>';
                                            } elseif ($row['status'] == 1) {
                                                echo '<span class="badge bg-info text-dark"><i class="fas fa-spinner fa-spin me-1"></i>Processing</span>';
                                            } elseif ($row['status'] == 2) {
                                                echo '<span class="badge bg-success"><i class="fas fa-check-circle me-1"></i>Completed</span>';
                                            } else {
                                                echo '<span class="badge bg-danger"><i class="fas fa-times-circle me-1"></i>Rejected</span>';
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <?php if (!empty($row['result_file'])): ?>
                                                <a href="<?= htmlspecialchars($row['result_file']); ?>" class="btn btn-sm btn-success fw-bold px-3" download>
                                                    <i class="fas fa-cloud-download-alt me-1"></i>Download
                                                </a>
                                            <?php else: ?>
                                                <button class="btn btn-sm btn-secondary" disabled><i class="fas fa-times-circle me-1"></i>No File</button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-muted py-3">No tracking metrics matching user identifier 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: 'Submission Failed',
    text: '<?= addslashes($errorMsg); ?>'
});
</script>
<?php endif; ?>

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

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