<?php
/**
 * IBVTE - Detailed NOC & ID Card Application
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$db = DB();
$step = isset($_GET['step']) ? intval($_GET['step']) : 1;
if ($step < 1 || $step > 3) $step = 1;

$errors = [];
$success_app_no = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Step 1: Proceed to Step 2
    if (isset($_POST['proceed_step2'])) {
        header('Location: apply-detailed.php?step=2');
        exit;
    }
    
    // Step 2: Submit Registration
    if (isset($_POST['submit_registration'])) {
        $appType = cleanInput($_POST['application_type'] ?? '');
        $docType = cleanInput($_POST['document_type'] ?? '');
        $name = cleanInput($_POST['applicant_name'] ?? '');
        $email = cleanInput($_POST['email'] ?? '');
        $mobile = cleanInput($_POST['mobile'] ?? '');
        $feeStatus = cleanInput($_POST['fee_status'] ?? 'pay_now');
        $fee = 500.00;
        
        if (empty($name) || empty($email) || empty($mobile)) {
            $errors[] = "Please fill all required fields.";
        } else {
            $appNo = 'NOC-' . date('Ymd') . rand(1000, 9999);
            
            try {
                $insertedId = $db->insert('noc_applications', [
                    'application_no' => $appNo,
                    'applicant_name' => $name,
                    'email' => $email,
                    'mobile' => $mobile,
                    'application_type' => $appType,
                    'document_type' => $docType,
                    'fee_amount' => $fee,
                    'payment_mode' => ($feeStatus === 'already_submitted' ? 'already_submitted' : 'online'),
                    'status' => 'pending'
                ]);
                
                $_SESSION['last_noc_id'] = $insertedId;
                $_SESSION['last_noc_no'] = $appNo;
                
                if ($feeStatus === 'already_submitted') {
                    $_SESSION['noc_success'] = true;
                    header('Location: apply-detailed.php?step=3&success=1');
                } else {
                    header('Location: apply-detailed.php?step=3');
                }
                exit;
            } catch (Exception $e) {
                $errors[] = "Submission failed: " . $e->getMessage();
            }
        }
    }
    
    // Step 3: Fee Payment / Final Submit
    if (isset($_POST['submit_payment'])) {
        $paymentMode = $_POST['payment_mode'] ?? 'online';
        $appId = $_SESSION['last_noc_id'] ?? null;
        
        if (!$appId) {
            $errors[] = "Session expired. Please start again.";
        } else {
            $data = ['payment_mode' => $paymentMode];
            
            if ($paymentMode === 'online') {
                if (isset($_FILES['screenshot']) && $_FILES['screenshot']['error'] === 0) {
                    $uploadDir = __DIR__ . '/../assets/uploads/noc_payments/';
                    if (!is_dir($uploadDir)) {
                        @mkdir($uploadDir, 0777, true);
                    }
                    
                    $filename = 'PAY_' . $_SESSION['last_noc_no'] . '_' . time() . '.' . pathinfo($_FILES['screenshot']['name'], PATHINFO_EXTENSION);
                    $targetPath = $uploadDir . $filename;
                    
                    if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $targetPath)) {
                        $data['payment_screenshot'] = $filename;
                    } else {
                        $errors[] = "Failed to upload screenshot. Please check folder permissions.";
                    }
                } else {
                    $errors[] = "Please upload payment screenshot.";
                }
            }
            
            if (empty($errors)) {
                $db->update('noc_applications', $data, ['id' => $appId]);
                $_SESSION['noc_success'] = true;
                header('Location: apply-detailed.php?step=3&success=1');
                exit;
            }
        }
    }
}

$success = isset($_GET['success']) && isset($_SESSION['noc_success']);
$currentAppNo = $_SESSION['last_noc_no'] ?? '';

include __DIR__ . '/../includes/header.php';
?>

<!-- Success Modal -->
<?php if ($success): ?>
<div class="modal fade shadow" id="successModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0" style="border-radius: 20px;">
            <div class="modal-body text-center p-5">
                <div class="mb-4">
                    <i class="fas fa-check-circle fa-5x text-success animate__animated animate__bounceIn"></i>
                </div>
                <h2 class="fw-bold text-dark mb-2">Submit Successful!</h2>
                <p class="text-muted mb-4">Your application has been received. Please note your Application Number for future reference.</p>
                
                <div class="bg-light p-3 rounded-3 mb-4 border">
                    <small class="text-uppercase fw-bold text-muted d-block mb-1">Application Number</small>
                    <h3 class="fw-bold text-primary mb-0"><?php echo htmlspecialchars($currentAppNo); ?></h3>
                </div>
                
                <button type="button" class="btn btn-primary btn-lg w-100 rounded-pill py-3" onclick="window.location.href='../index.php'">
                    Go to Home Page
                </button>
            </div>
        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        var myModal = new bootstrap.Modal(document.getElementById('successModal'));
        myModal.show();
    });
</script>
<?php 
    unset($_SESSION['noc_success']);
    endif; 
?>

<section class="py-4" style="background: linear-gradient(135deg, #5a2d8c 0%, #7c4db8 100%);">
    <div class="container">
        <div class="text-center text-white">
            <h2 class="fw-bold mb-2"><i class="fas fa-file-signature me-2"></i>NOC & ID Card Application</h2>
            <p class="mb-0">Pre-Requisite and Instructions for Final Diploma Of Paramedical Course</p>
        </div>
    </div>
</section>

<section class="py-5">
    <div class="container">
        <!-- Progress Steps -->
        <div class="row mb-5">
            <div class="col-md-8 offset-md-2">
                <div class="d-flex justify-content-between position-relative">
                    <div class="progress" style="height: 4px; position: absolute; top: 20px; left: 0; right: 0; z-index: 0;">
                        <div class="progress-bar" style="width: <?php echo (($step - 1) * 50); ?>%; background: #5a2d8c;"></div>
                    </div>
                    
                    <div class="step-item text-center" style="z-index: 1;">
                        <div class="rounded-circle d-flex align-items-center justify-content-center mx-auto mb-2 shadow-sm" 
                             style="width: 45px; height: 45px; background: <?php echo ($step >= 1) ? '#5a2d8c' : '#e0e0e0'; ?>; color: white; font-weight: bold;">1</div>
                        <small class="fw-bold <?php echo ($step >= 1) ? 'text-primary' : 'text-muted'; ?>">Instructions</small>
                    </div>
                    
                    <div class="step-item text-center" style="z-index: 1;">
                        <div class="rounded-circle d-flex align-items-center justify-content-center mx-auto mb-2 shadow-sm" 
                             style="width: 45px; height: 45px; background: <?php echo ($step >= 2) ? '#5a2d8c' : '#e0e0e0'; ?>; color: white; font-weight: bold;">2</div>
                        <small class="fw-bold <?php echo ($step >= 2) ? 'text-primary' : 'text-muted'; ?>">Registration</small>
                    </div>
                    
                    <div class="step-item text-center" style="z-index: 1;">
                        <div class="rounded-circle d-flex align-items-center justify-content-center mx-auto mb-2 shadow-sm" 
                             style="width: 45px; height: 45px; background: <?php echo ($step >= 3) ? '#5a2d8c' : '#e0e0e0'; ?>; color: white; font-weight: bold;">3</div>
                        <small class="fw-bold <?php echo ($step >= 3) ? 'text-primary' : 'text-muted'; ?>">Fee Payment</small>
                    </div>
                </div>
            </div>
        </div>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm" style="border-radius:10px;">
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                <?php foreach ($errors as $error): ?>
                    <p class="mb-1"><i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($step == 1): ?>
        <!-- STEP 1: Instructions -->
        <div class="card shadow-lg border-0" style="border-radius: 15px;">
            <div class="card-header text-white py-3" style="background: linear-gradient(135deg, #5a2d8c, #7c4db8); border-radius: 15px 15px 0 0;">
                <h4 class="mb-0"><i class="fas fa-info-circle me-2"></i>Pre-Requisite and Instructions</h4>
            </div>
            <div class="card-body p-4">
                <p class="mb-3">Kindly arrange the scanned images of original documents for the followings <strong>(Note : Scanned copy of photocopy is not acceptable)</strong> :</p>

                <form method="POST" action="">
                    <!-- For ID Card Section -->
                    <div class="mb-4">
                        <h5 class="fw-bold text-primary border-bottom pb-2 mb-3">For Id Card</h5>
                        <ul class="list-unstyled">
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Certificate and Marksheet of High School and Intermediate</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Marksheets of ParaMedical Course</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Degree/ Provisional Degree of ParaMedical Course</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Provisional Internship Certificate issued by Board</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Internship Certificate issued by Medical College</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Internship Certificate issued by Hospital</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Affidavit</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Voter ID card/Adhaar card/ Driving licence/Passport</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Photograph (File Format .jpg, .png, .gif, Max. Size 50 kb, resolution 250px x 300px)</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Signature (File Format .jpg, .png, .gif, Max. Size 50 kb, resolution 150px x 75px)</li>
                        </ul>
                    </div>

                    <!-- For NOC Section -->
                    <div class="mb-4">
                        <h5 class="fw-bold text-primary border-bottom pb-2 mb-3">For Noc</h5>
                        <ul class="list-unstyled">
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Board Registration Certificate (max file size 100kb only jpg file formats are allowed)</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Board ID Card (max file size 100kb only jpg file formats are allowed)</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Voter ID card/Adhaar card/ Driving licence/Passport</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Photograph (File Format .jpg, .png, .gif, Max. Size 50 kb, resolution 250px x 300px)</li>
                            <li class="mb-2"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Signature (File Format .jpg, .png, .gif, Max. Size 50 kb, resolution 150px x 75px)</li>
                        </ul>
                    </div>
                    
                    <!-- Process for Form Filling -->
                    <div class="mb-4">
                        <h5 class="fw-bold text-primary border-bottom pb-2 mb-3">Process for Form Filling :</h5>
                        <ul class="list-unstyled">
                            <li class="mb-2 fw-bold"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Step 1 :</li>
                            <ol>
                                <li>Click on "Registration (Step 1)" link</li>
                                <li>Enter valid information in online registration form, then click on submit button.</li>
                                <li>You will get your Application No. and Applicant ID, after successful registration.</li>
                            </ol>
                            
                            <li class="mb-2 fw-bold mt-3"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Step 2 :</li>
                            <ol>
                                <li>User will go to 2nd step,He/She will login and fill his/her basic information,Then fill the Qualification details and upload the Documents!</li>
                                <li>You will be required to login with your user name and password where user name will be your Applicant ID and password will be your Bank Reference No.</li>
                            </ol>
                            
                            <li class="mb-2 fw-bold mt-3"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>Step 3 :</li>
                            <ol>
                                <li>Click on "Fee Payment (Step 3)" link after 24 hours of successful registration.</li>
                                <li>During transaction of State Bank payment enter your Application Id(12 Digit Id) and Date of Birth then click on submit button.</li>
                                <li>Print your E-Receipt after successful payment.</li>
                            </ol>
                            
                            <li class="mb-2 fw-bold mt-3 text-danger"><i class="fas fa-circle" style="font-size: 8px; vertical-align: middle; margin-right: 10px;"></i>NOTE :</li>
                            <ol class="text-danger">
                                <li>1. Bank Draft for the verification of documents will be send through Registered Post at Council of 2nd Floor Sunil Complex Near RG PG College Meerut (UP)- 250002</li>
                            </ol>
                        </ul>
                    </div>

                    <div class="text-center mt-5">
                        <button type="submit" name="proceed_step2" class="btn btn-lg px-5 shadow" style="background: linear-gradient(135deg, #5a2d8c, #7c4db8); color: white; border-radius: 30px;">
                            <i class="fas fa-arrow-right me-2"></i>Proceed
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <?php elseif ($step == 2): ?>
        <!-- STEP 2: Application Form -->
        <div class="card shadow-lg border-0" style="border-radius: 15px;">
            <div class="card-header text-white py-3" style="background: linear-gradient(135deg, #5a2d8c, #7c4db8); border-radius: 15px 15px 0 0;">
                <h4 class="mb-0"><i class="fas fa-edit me-2"></i>Application for NOC & ID Card</h4>
            </div>
            <div class="card-body p-4">
                <div class="alert alert-warning mb-4 border-0" style="background:#fff3cd; border-radius:10px;">
                    <small><strong>*</strong> Please update all Information/ Details in English</small>
                </div>

                <form method="POST" action="" enctype="multipart/form-data">
                    <div class="row mb-3">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Application For <span class="text-danger">*</span></label>
                            <select class="form-select form-control-lg border-2" name="application_type" required>
                                <option value="">Select</option>
                                <option value="noc">NOC</option>
                                <option value="id_card">ID Card</option>
                                <option value="both">Both NOC & ID Card</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Document <span class="text-danger">*</span></label>
                            <select class="form-select form-control-lg border-2" name="document_type" required>
                                <option value="">Select</option>
                                <option value="final_diploma">Final Diploma</option>
                                <option value="provisional">Provisional</option>
                                <option value="migration">Migration</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control form-control-lg border-2" name="applicant_name" placeholder="Enter your full name" required>
                        <small class="text-muted">Please do not use title such as "Dr./Mr./Mrs./Ms." along with your name</small>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Email ID <span class="text-danger">*</span></label>
                            <input type="email" class="form-control form-control-lg border-2" name="email" placeholder="Enter email address" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Confirm Email ID <span class="text-danger">*</span></label>
                            <input type="email" class="form-control form-control-lg border-2" name="confirm_email" placeholder="Confirm email address" required>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Mobile No. <span class="text-danger">*</span></label>
                            <input type="tel" class="form-control form-control-lg border-2" name="mobile" placeholder="Enter 10-digit mobile number" pattern="[0-9]{10}" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Fee Payment Status <span class="text-danger">*</span></label>
                            <select class="form-select form-control-lg border-2" name="fee_status" required onchange="updateFeeLabel(this.value)">
                                <option value="pay_now">Pay Now (₹ 500)</option>
                                <option value="already_submitted">Already Submitted / Offline</option>
                            </select>
                        </div>
                    </div>

                    <div class="d-flex justify-content-between mt-4">
                        <a href="apply-detailed.php?step=1" class="btn btn-outline-secondary btn-lg px-4" style="border-radius:30px;">
                            <i class="fas fa-arrow-left me-2"></i>Back
                        </a>
                        <button type="submit" name="submit_registration" class="btn btn-lg px-5 shadow" style="background: linear-gradient(135deg, #5a2d8c, #7c4db8); color: white; border-radius:30px;">
                            <i class="fas fa-paper-plane me-2"></i>Submit Application
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <?php elseif ($step == 3): ?>
        <!-- STEP 3: Fee Payment -->
        <div class="card shadow-lg border-0" style="border-radius: 15px;">
            <div class="card-header text-white py-3" style="background: linear-gradient(135deg, #5a2d8c, #7c4db8); border-radius: 15px 15px 0 0;">
                <h4 class="mb-0"><i class="fas fa-credit-card me-2"></i>Fee Payment</h4>
            </div>
            <div class="card-body p-4">
                <div class="row justify-content-center">
                    <div class="col-md-8">
                        <div class="text-center mb-4">
                            <div class="bg-light p-3 rounded-3 mb-3 border">
                                <small class="text-uppercase fw-bold text-muted">Application Number</small>
                                <h4 class="fw-bold text-primary mb-0"><?php echo htmlspecialchars($currentAppNo); ?></h4>
                            </div>
                        </div>

                        <form method="POST" action="" enctype="multipart/form-data">
                            <div class="mb-4">
                                <label class="form-label fw-bold">Payment Mode <span class="text-danger">*</span></label>
                                <select class="form-select form-control-lg border-2" name="payment_mode" id="paymentMode" required onchange="toggleScreenshot(this.value)">
                                    <option value="online">Pay Online (Upload Screenshot)</option>
                                    <option value="already_submitted">Already Submitted / Offline</option>
                                </select>
                            </div>

                            <div id="screenshotSection" class="mb-4">
                                <div class="card border-2 bg-light border-dashed">
                                    <div class="card-body text-center py-4">
                                        <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                        <h6 class="fw-bold">Upload Payment Screenshot</h6>
                                        <p class="small text-muted mb-3">JPEG, PNG only (Max 2MB)</p>
                                        <input type="file" class="form-control" name="screenshot" id="screenshotInput" accept="image/*">
                                    </div>
                                </div>
                            </div>

                            <div class="alert alert-info border-0" style="background:#e7f3ff; border-radius:10px;">
                                <p class="mb-0 small"><i class="fas fa-info-circle me-2"></i>
                                If you chose 'Already Submitted', your application will be verified based on your registration details. If 'Pay Online', please upload the QR code / Bank transfer success screen.</p>
                            </div>

                            <div class="d-flex justify-content-between mt-5">
                                <a href="apply-detailed.php?step=2" class="btn btn-outline-secondary btn-lg px-4" style="border-radius:30px;">
                                    <i class="fas fa-arrow-left me-2"></i>Back
                                </a>
                                <button type="submit" name="submit_payment" class="btn btn-lg px-5 shadow" style="background: linear-gradient(135deg, #5a2d8c, #7c4db8); color: white; border-radius:30px;">
                                    <i class="fas fa-check-circle me-2"></i>Final Submit
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <script>
            function toggleScreenshot(mode) {
                const section = document.getElementById('screenshotSection');
                const input = document.getElementById('screenshotInput');
                if (mode === 'already_submitted') {
                    section.style.display = 'none';
                    input.required = false;
                } else {
                    section.style.display = 'block';
                    input.required = true;
                }
            }
            // Initialize on load
            if(document.getElementById('paymentMode')) {
                toggleScreenshot(document.getElementById('paymentMode').value);
            }
        </script>
        <?php endif; ?>

    </div>
</section>

<?php include __DIR__ . '/../includes/footer.php'; ?>
