<?php
require_once("../includes/session.php");
require_once("../includes/config.php");

if (!in_array($udata['type'], ['Master Distributor', 'Distributor', 'Retailer', 'admin'])) {
    require_once("404.php");
    exit;
}

if (!isset($udata['tec_exam_service']) || $udata['tec_exam_service'] != 'YES') {
    echo '<script>
        Swal.fire("Access Denied", "TEC Exam service not active!", "info");
        setTimeout(function(){ window.location="index.php"; }, 2000);
    </script>';
    exit;
}

$show_popup = false;
$popup_order_id = '';
$popup_roll_number = '';

if (isset($_POST['submit'])) {
    $exam_type = trim($_POST['exam_type']);
    $roll_number = strtoupper(trim($_POST['roll_number']));
    $year = trim($_POST['year']);
    
    if (empty($exam_type) || empty($roll_number) || empty($year)) {
        echo '<script>Swal.fire("Error", "All fields required!", "error");</script>';
    } else {
        $amount = floatval($udata['tec_exam_fee'] ?? 45);
        $old_balance = floatval($udata['balance'] ?? 0);
        $new_balance = $old_balance - $amount;
        
        if ($old_balance < $amount) {
            echo '<script>Swal.fire("Insufficient Balance", "Need: ₹' . $amount . '", "error");</script>';
        } else {
            $order_id = 'TEC' . time() . rand(1000, 9999);
            
            $updateSuccess = mysqli_query($ahk_conn, "UPDATE users SET balance = $new_balance WHERE phone = '{$udata['phone']}'");
            
            if ($updateSuccess) {
                $requestSql = "INSERT INTO tec_exam_requests (
                    user_id, username, name, mobile, order_id, exam_type, roll_number, year,
                    amount, status, request_date
                ) VALUES (
                    '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['phone']}',
                    '$order_id', '$exam_type', '$roll_number', '$year', $amount, 'Pending', NOW()
                )";
                
                $insertSuccess = mysqli_query($ahk_conn, $requestSql);
                
                if ($insertSuccess) {
                    $reportSql = "INSERT INTO reports (
                        site_id, user_id, username, name, operator, parent_id, order_id, service, type,
                        account_number, app_type, amount, main_amount, old_balance, new_balance,
                        txn_id, ref_id, description, date_time, status
                    ) VALUES (
                        1, '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['type']}', 0,
                        '$order_id', 'TEC Exam Certificate', 'Debit', '$roll_number', 'TEC Exam',
                        $amount, $amount, $old_balance, $new_balance, '$order_id', '$roll_number',
                        'TEC Exam Certificate - Rs.$amount debit', NOW(), 'Success'
                    )";
                    mysqli_query($ahk_conn, $reportSql);
                    
                    $whamessage = "Dear {$udata['name']},\n\nTEC Exam Request Submitted!\n\nOrder ID: {$order_id}\nExam: {$exam_type}\nRoll No: {$roll_number}\n\nProcessing: 30 min";
                    @send_sms($udata['phone'], $whamessage);
                    
                    $show_popup = true;
                    $popup_order_id = $order_id;
                    $popup_roll_number = $roll_number;
                    
                } else {
                    mysqli_query($ahk_conn, "UPDATE users SET balance = $old_balance WHERE phone = '{$udata['phone']}'");
                    echo '<script>Swal.fire("Error", "Failed. Balance restored.", "error");</script>';
                }
            } else {
                echo '<script>Swal.fire("Error", "Balance update failed!", "error");</script>';
            }
        }
    }
}

include('../template/ahkweb/header.php');
?>

<?php if($show_popup): ?>
<div class="popup-overlay" id="successPopup" style="display:flex;">
    <div class="popup-box">
        <div class="success-icon">✅</div>
        <h3>TEC Exam Request Submitted!</h3>
        
        <div style="background:#f5f5f5;padding:15px;border-radius:10px;margin:20px 0;">
            <p><strong>Order ID:</strong> <?=$popup_order_id?></p>
            <p><strong>Roll Number:</strong> <?=$popup_roll_number?></p>
        </div>
        
        <div style="background:linear-gradient(135deg,#e1f5fe,#b3e5fc);padding:20px;border-radius:10px;text-align:center;">
            <h4 style="color:#0277bd;">⏱️ Processing: 30 minutes</h4>
        </div>
        
        <button onclick="window.location='tec_exam_list.php'" style="width:100%;background:#2196f3;color:white;border:none;padding:12px;border-radius:8px;cursor:pointer;margin-top:10px;">
            OK, Got It!
        </button>
    </div>
</div>
<script>
setTimeout(function(){ window.location='tec_exam_list.php'; }, 5000);
</script>
<?php endif; ?>

<style>
.popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 9999;
}
.popup-box {
    background: white;
    border-radius: 15px;
    padding: 30px;
    max-width: 450px;
    width: 90%;
    box-shadow: 0 10px 40px rgba(0,0,0,0.3);
}
.success-icon {
    font-size: 60px;
    text-align: center;
    margin-bottom: 15px;
}
</style>

<div class="page-wrapper">
    <div class="page-content">
        <div class="row">
            <div class="col-md-5 mb-3">
                <div class="card">
                    <div class="card-header bg-info text-white py-2">
                        <div class="d-flex align-items-center">
                            <span><i class="fas fa-graduation-cap"></i> TEC Direct Exam Certificate</span>
                            <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
                        </div>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label><strong>Exam Type <span class="text-danger">*</span></strong></label>
                                <select name="exam_type" class="form-control" required>
                                    <option value="">-- Select Exam --</option>
                                    <option>Diploma</option>
                                    <option>Polytechnic</option>
                                    <option>ITI</option>
                                    <option>Engineering</option>
                                    <option>Other Technical</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label><strong>Roll Number <span class="text-danger">*</span></strong></label>
                                <input type="text" name="roll_number" class="form-control" placeholder="Enter Roll Number" 
                                       maxlength="30" oninput="this.value=this.value.toUpperCase()" required>
                            </div>
                            
                            <div class="mb-3">
                                <label><strong>Year <span class="text-danger">*</span></strong></label>
                                <select name="year" class="form-control" required>
                                    <option value="">-- Select Year --</option>
                                    <?php for($y=date('Y'); $y>=2000; $y--): ?>
                                    <option><?php echo $y; ?></option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-3">
                                <button type="button" class="btn btn-secondary">₹<?php echo number_format($udata['tec_exam_fee'] ?? 45, 2); ?></button>
                                <button type="submit" name="submit" class="btn btn-info" onclick="return confirm('Submit?');">
                                    <i class="fas fa-paper-plane"></i> Submit
                                </button>
                                <a href="tec_exam_list.php" class="btn btn-warning"><i class="fas fa-list"></i> My Requests</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-7 mb-3">
                <div class="card">
                    <div class="card-header bg-info text-white py-2">
                        <span>📋 Service Information</span>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <h5><i class="fas fa-info-circle"></i> Service Details</h5>
                            <ul>
                                <li><b>Service:</b> TEC Direct Exam Certificate</li>
                                <li><b>Amount:</b> ₹<?php echo number_format($udata['tec_exam_fee'] ?? 45, 2); ?></li>
                                <li><b>Processing:</b> 30 minutes</li>
                            </ul>
                        </div>
                        
                        <div class="alert alert-warning">
                            <h5><i class="fas fa-exclamation-triangle"></i> Important</h5>
                            <ul>
                                <li>Certificate PDF मिलेगी</li>
                                <li>Roll Number सही भरें</li>
                                <li>Exam Type और Year select करें</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include('../admin/footers.php'); ?>