<?php 
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');

// Fixed fee (from API response shows 40)
define('LL_EXAM_FEE', 80);

$balance = $udata['balance'];
$mobile = $udata['phone'];

if (isset($_POST['submit_exam']) && !empty($_POST['application_no']) && !empty($_POST['applicant_name']) && !empty($_POST['dob']) && !empty($_POST['password'])) {
    
    if ($balance < LL_EXAM_FEE) {
        echo "<script>
            Swal.fire({
                title:'Balance Low! Recharge Now',
                text:'Insufficient Balance',
                icon:'warning',
                confirmButtonText:'OK'
            }).then((result) => { if(result.isConfirmed) window.location='wallet.php'; });
        </script>";
    } else {
        $application_no = trim($_POST['application_no']);
        $applicant_name = trim($_POST['applicant_name']);
        $dob_raw = trim($_POST['dob']);
        $password = trim($_POST['password']);

        // Convert DOB from YYYY-MM-DD (HTML date) to DD-MM-YYYY (Pariprint API format)
        $dob = $dob_raw;
        if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $dob_raw, $m)) {
            $dob = $m[3] . '-' . $m[2] . '-' . $m[1];
        }

        // PARIPRINT API ENDPOINT (Dynamic from Central Manager)
        $apiBase = (function_exists('get_central_api_domain') ? rtrim(get_central_api_domain(), '/') : 'https://pariprint.in');
        $apiUrl = $apiBase . "/api-proxy.php?" . http_build_query([
            'slug'         => 'instant-ll-pass',
            'app_no'       => $application_no,
            'dob'          => $dob,
            'password'     => $password,
            'api_key'      => $pariprint_api_key
        ]);
        
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_USERAGENT => 'goodprintportal.in-ll-exam',
        ));
        
        $response = curl_exec($ch);
        $curlError = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($response === false || !empty($curlError)) {
            echo '<div class="alert alert-danger">API Connection Failed: ' . htmlspecialchars($curlError) . '</div>';
        } else {
            $data = json_decode($response, true);
            $status = $data['status'] ?? $data['success'] ?? false;
            $message = $data['message'] ?? 'No response message';
            $resultValue = $data['result_value'] ?? '';
            $requestId = $data['request_id'] ?? $data['order_id'] ?? '';
            $chargeAmount = isset($data['charge_amount']) ? (float) $data['charge_amount'] : LL_EXAM_FEE;

            $fee = LL_EXAM_FEE;
            $new_balance_calc = $balance - $fee;

            $application_no_resp = $application_no;
            $applicant_name_resp = $applicant_name;
            $tracking_id = $requestId !== '' ? $requestId : ('LL' . time() . rand(100, 999));
            $api_transaction_id = $requestId;

            $apiMessage = trim($resultValue) !== '' ? $resultValue : $message;

            $isSuccess = (
                $status === true ||
                $status === 1 ||
                $status === 'true' ||
                $status === 'SUCCESS' ||
                $status === 'success'
            );
            
            if ($isSuccess) {
                // Update local wallet balance
                mysqli_query($ahk_conn, "UPDATE users SET balance = balance - " . $fee . " WHERE phone='$mobile'");
                
                date_default_timezone_set("Asia/Kolkata");
                $timestamp = date('d/m/Y g:i:s');
                
                $statusForDb = 'pending';
                // If pariprint already includes pass/fail in message, mark accordingly
                $msgLower = strtolower($apiMessage);
                if (strpos($msgLower, 'pass') !== false || strpos($msgLower, 'successful') !== false) {
                    $statusForDb = 'passed';
                } elseif (strpos($msgLower, 'fail') !== false || strpos($msgLower, 'reject') !== false) {
                    $statusForDb = 'rejected';
                }

                $safe_app_no = mysqli_real_escape_string($ahk_conn, $application_no_resp);
                $safe_app_name = mysqli_real_escape_string($ahk_conn, $applicant_name_resp);
                $safe_dob = mysqli_real_escape_string($ahk_conn, $dob_raw);
                $safe_pwd = mysqli_real_escape_string($ahk_conn, $password);
                $safe_tracking = mysqli_real_escape_string($ahk_conn, $tracking_id);
                $safe_api_txn = mysqli_real_escape_string($ahk_conn, $api_transaction_id);
                $safe_status = mysqli_real_escape_string($ahk_conn, $statusForDb);
                $safe_mobile = mysqli_real_escape_string($ahk_conn, $mobile);
                $safe_date = mysqli_real_escape_string($ahk_conn, $timestamp);
                $safe_fee = mysqli_real_escape_string($ahk_conn, $fee);

                // Insert into ll_exam_list table
                $insert = mysqli_query($ahk_conn, "INSERT INTO ll_exam_list(
                    application_no, 
                    applicant_name, 
                    dob, 
                    password, 
                    tracking_id, 
                    api_transaction_id, 
                    status, 
                    userid, 
                    date, 
                    amount
                ) VALUES (
                    '$safe_app_no', 
                    '$safe_app_name', 
                    '$safe_dob', 
                    '$safe_pwd', 
                    '$safe_tracking', 
                    '$safe_api_txn', 
                    '$safe_status', 
                    '$safe_mobile', 
                    '$safe_date', 
                    '$safe_fee'
                )");
                
                // Insert wallet history
                $safe_new_bal = mysqli_real_escape_string($ahk_conn, $new_balance_calc);
                $safe_purpose = mysqli_real_escape_string($ahk_conn, 'LL Exam - ' . $applicant_name_resp);
                mysqli_query($ahk_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type) 
                    VALUES ('$safe_mobile', '$safe_fee', '$safe_new_bal', '$safe_purpose', '1', 'Debit')");
                
                $displayMsg = "LL Exam Request Submitted Successfully!\n\nApp No: $application_no\nName: $applicant_name\nDOB: $dob\n\n" . $apiMessage;
                $displayMsgJs = json_encode($displayMsg, JSON_UNESCAPED_UNICODE);

                echo "<script>
                    Swal.fire({
                        title:'Success!',
                        text: $displayMsgJs,
                        icon:'success',
                        confirmButtonText:'Go to LL Exam List'
                    }).then(() => { window.location='ll_request_list.php'; });
                </script>";
            } else {
                $displayMsg = "LL Exam Request Failed.\n\nApp No: $application_no\nName: $applicant_name\n\nReason: " . $apiMessage;
                $displayMsgJs = json_encode($displayMsg, JSON_UNESCAPED_UNICODE);
                echo "<script>
                    Swal.fire({
                        title:'Error',
                        text: $displayMsgJs,
                        icon:'error',
                        confirmButtonText:'OK'
                    });
                </script>";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Learning Licence Exam | Apply Online</title>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        :root {
            --primary: #4361ee;
            --primary-dark: #3a56d4;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
        }
        body {
            background: linear-gradient(135deg, #f5f7fc 0%, #eef2f9 100%);
        }
        .exam-card {
            background: rgba(255,255,255,0.98);
            backdrop-filter: blur(0px);
            border: none;
            border-radius: 2rem;
            box-shadow: 0 25px 45px -12px rgba(0,0,0,0.2);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .exam-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 30px 55px -15px rgba(0,0,0,0.25);
        }
        .fee-chip {
            background: linear-gradient(135deg, #ff9a3c, #ff6a00);
            border-radius: 60px;
            padding: 0.5rem 1.8rem;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            color: white;
            font-weight: 700;
            font-size: 1.3rem;
            box-shadow: 0 8px 18px rgba(255,106,0,0.3);
        }
        .form-input {
            border-radius: 60px;
            padding: 0.9rem 1.5rem;
            border: 2px solid #e2e8f0;
            transition: all 0.2s;
            font-size: 1rem;
        }
        .form-input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(67,97,238,0.15);
            outline: none;
        }
        .submit-btn {
            background: linear-gradient(90deg, var(--primary), var(--primary-dark));
            border: none;
            padding: 0.9rem;
            font-weight: 700;
            font-size: 1.1rem;
            border-radius: 60px;
            transition: all 0.3s;
            letter-spacing: 0.5px;
        }
        .submit-btn:hover {
            background: linear-gradient(90deg, var(--primary-dark), #2c3e9e);
            transform: scale(1.02);
            box-shadow: 0 10px 25px rgba(67,97,238,0.4);
        }
        .balance-card {
            background: white;
            border-radius: 1.5rem;
            border-left: 5px solid var(--success);
        }
        .credit-footer {
            background: linear-gradient(135deg, #1a1a2e, #16213e);
            color: #cbd5e1;
            border-radius: 1rem;
            padding: 0.8rem 1.5rem;
            font-size: 0.85rem;
            margin-top: 2rem;
        }
        .badge-delivery {
            background: #eef2ff;
            color: var(--primary);
            border-radius: 40px;
            padding: 0.4rem 1rem;
        }
        .feature-icon {
            background: #f1f5f9;
            width: 38px;
            height: 38px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 60px;
        }
    </style>
</head>
<body>

<div class="page-wrapper">
    <div class="page-content">
        <div class="container-fluid py-4">
            <div class="row justify-content-center">
                <div class="col-lg-6 col-md-8 col-12">
                    
                    <!-- Header with breadcrumb -->
                    <div class="d-flex flex-wrap align-items-center justify-content-between mb-4">
                        <div>
                            <h3 class="fw-bold mb-0 d-flex align-items-center gap-2">
                                <i class="bi bi-mortarboard-fill text-primary fs-2"></i> 
                                <span>Learning Licence Exam</span>
                            </h3>
                            <p class="text-muted mt-1">Apply for Learning Licence Exam - Results in 3-24 hours</p>
                        </div>
                        <div class="btn-group shadow-sm">
                            <a href="ll_request_list.php" class="btn btn-success rounded-pill px-3">
                                <i class="bi bi-list-ul"></i> My Applications
                            </a>
                            <a href="javascript:history.back()" class="btn btn-outline-secondary rounded-pill px-3">
                                <i class="bi bi-arrow-left"></i> Back
                            </a>
                        </div>
                    </div>

                    <!-- Balance Alert if low -->
                    <?php if ($balance < LL_EXAM_FEE): ?>
                        <div class="alert alert-warning d-flex align-items-center rounded-4 border-0 shadow-sm">
                            <i class="bi bi-exclamation-triangle-fill me-3 fs-4"></i>
                            <div>Insufficient balance. <a href="wallet.php" class="alert-link fw-bold">Recharge now</a> to continue.</div>
                        </div>
                    <?php endif; ?>

                    <!-- Main Card -->
                    <div class="card exam-card mb-4">
                        <div class="card-body p-4 p-lg-5">
                            <!-- Powered by badge -->
                            <div class="text-center mb-3">
                                <span class="badge bg-light text-dark px-3 py-2 rounded-pill shadow-sm">
                                    <i class="bi bi-lightning-charge-fill text-warning"></i> Powered by <strong class="text-primary">PARIPRINT.IN</strong>
                                </span>
                            </div>
                            
                            <div class="text-center mb-4">
                                <div class="fee-chip">
                                    <i class="bi bi-tag-fill"></i> ₹<?php echo LL_EXAM_FEE; ?> / Application
                                </div>
                                <div class="mt-3 d-flex justify-content-center gap-3 flex-wrap">
                                    <span class="badge-delivery"><i class="bi bi-clock-history"></i> 3-24 hours delivery</span>
                                    <span class="badge-delivery"><i class="bi bi-check-circle-fill text-success"></i> Instant Confirmation</span>
                                </div>
                            </div>
                            
                            <!-- Balance Card -->
                            <div class="balance-card p-3 mb-4 d-flex justify-content-between align-items-center shadow-sm">
                                <div>
                                    <i class="bi bi-wallet2 fs-4 text-success"></i>
                                    <span class="fw-semibold ms-2">Available Balance</span>
                                </div>
                                <div class="fs-4 fw-bold">₹<?php echo number_format($balance, 2); ?></div>
                                <?php if ($balance >= LL_EXAM_FEE): ?>
                                    <a href="wallet.php" class="btn btn-sm btn-outline-secondary rounded-pill">Recharge</a>
                                <?php else: ?>
                                    <a href="wallet.php" class="btn btn-sm btn-warning rounded-pill">Add Money</a>
                                <?php endif; ?>
                            </div>

                            <form method="POST">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold mb-2">
                                        <i class="bi bi-upc-scan"></i> Application Number
                                    </label>
                                    <input type="text" 
                                           name="application_no" 
                                           class="form-control form-input" 
                                           placeholder="Enter your Application Number" 
                                           required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label fw-semibold mb-2">
                                        <i class="bi bi-person-fill"></i> Applicant Name
                                    </label>
                                    <input type="text" 
                                           name="applicant_name" 
                                           class="form-control form-input" 
                                           placeholder="Enter Full Name" 
                                           required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label fw-semibold mb-2">
                                        <i class="bi bi-calendar-fill"></i> Date of Birth
                                    </label>
                                    <input type="date" 
                                           name="dob" 
                                           class="form-control form-input" 
                                           required>
                                </div>
                                
                                <div class="mb-4">
                                    <label class="form-label fw-semibold mb-2">
                                        <i class="bi bi-key-fill"></i> Password
                                    </label>
                                    <input type="password" 
                                           name="password" 
                                           class="form-control form-input" 
                                           placeholder="Enter Password" 
                                           required>
                                    <div class="form-text mt-2">
                                        <i class="bi bi-info-circle"></i> This password will be used for exam login.
                                    </div>
                                </div>
                                
                                <button type="submit" name="submit_exam" class="btn submit-btn w-100 text-white" <?php echo ($balance < LL_EXAM_FEE) ? 'disabled' : ''; ?>>
                                    <i class="bi bi-cloud-arrow-up-fill me-2"></i>
                                    <?php echo ($balance >= LL_EXAM_FEE) ? 'Submit & Pay ₹'.LL_EXAM_FEE : 'Insufficient Balance'; ?>
                                </button>
                            </form>

                            <!-- Features row -->
                            <div class="row mt-4 g-3 text-center">
                                <div class="col-4">
                                    <div class="feature-icon mx-auto mb-2"><i class="bi bi-shield-check text-primary fs-5"></i></div>
                                    <small class="text-muted">Secure & Verified</small>
                                </div>
                                <div class="col-4">
                                    <div class="feature-icon mx-auto mb-2"><i class="bi bi-hourglass-split text-warning fs-5"></i></div>
                                    <small class="text-muted">3-24 Hours Result</small>
                                </div>
                                <div class="col-4">
                                    <div class="feature-icon mx-auto mb-2"><i class="bi bi-headset text-success fs-5"></i></div>
                                    <small class="text-muted">24/7 Support</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Developer & Powered by Footer -->
                    <div class="credit-footer text-center">
                        <div class="d-flex flex-wrap justify-content-center gap-4 align-items-center">
                            <span><i class="bi bi-cpu"></i> Powered by <strong>PARIPRINT.IN</strong></span>
                            <span class="text-muted">|</span>
                            <span><i class="bi bi-code-slash"></i> Developed by <strong class="text-warning">Lala Web Developer</strong></span>
                        </div>
                        <div class="mt-2 small opacity-75">
                            <i class="bi bi-patch-check-fill text-success"></i> Official LL Exam Service
                        </div>
                    </div>

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

<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
</body>
</html>
<?php include('userFooter.php'); ?>