<!-- 
  **File Structure:**
  - school_step1.php (School Profile)
  - school_step2.php (School Land)
  - school_step3.php (School Building)
  - school_step4.php (School Facilities)
  - school_step5.php (School Posts)
  - school_step6.php (School Students)
  - school_step7.php (School Board Results)
  - school_step8.php (School Budget)
  - school_step9.php (School SMC)
  - school_step10.php (School Location and View)
  
  Here's the ninth file (school_step9.php):
    -->
  
<?php
// ============================================================================
// FILE: school_step9.php
// STEP: 9 of 10 - School Management Committee (SMC) Registration
// ============================================================================

// 1. SESSION & SECURITY
// Session started
require_once 'session_config_school.php';

// Validate school session
if (!validateSchoolSession()) {
    header("Location: login.php");
    exit;
}

// School Profile Completion Check
require_once 'school_profile_completion_check.php';

// Database connection
include_once 'connect.php';

// 2. INITIALIZATION
$success_message = '';
$error_message = '';
$form_data = [];

// Retrieve session variables
$school_name = $_SESSION['school_name'] ?? '';
$emis_code = $_SESSION['emis_code'] ?? '';
$cate_id = $_SESSION['cate_id'] ?? '';
$level_id = $_SESSION['level_id'] ?? '';


// Handle session messages
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}
if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}
if (isset($_SESSION['form_data'])) {
    $form_data = $_SESSION['form_data'];
    unset($_SESSION['form_data']);
}

// 3. FUNCTION: Fetch Existing SMC Data (Schema-compliant)
function getExistingSMCData($conn, $emis_code) {
    $smc_data = [];
    
    $query = "SELECT * FROM school_smc WHERE emis_code = ?";
    $stmt = $conn->prepare($query);
    if ($stmt) {
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            
            // Map database fields to form fields (matches your exact schema)
            $smc_data['smc_select'] = $row['smc_select'];
            $smc_data['smcactive'] = $row['smc_active'];
            $smc_data['smctraining'] = $row['smc_training'];
            $smc_data['smcp'] = $row['smc_president_name'];
            $smc_data['smcpc'] = $row['smc_president_contact'];
            $smc_data['smcbankaccount'] = $row['smc_bank_account'];
            $smc_data['smcbankname'] = $row['smc_bank_name'];
            $smc_data['smcbac'] = $row['smc_bank_account_number'];
            $smc_data['smcamount'] = $row['smc_amount_received'];
            $smc_data['nosmc'] = $row['no_smc_reason'];
        }
        $stmt->close();
    }
    return $smc_data;
}

// 4. FETCH EXISTING SMC DATA
if (!empty($emis_code)) {
    $existing_smc = getExistingSMCData($conn, $emis_code);
    if (!empty($existing_smc)) {
        $form_data = array_merge($form_data, $existing_smc);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>School Management Committee Registration - Step 9 of 10</title>
<!-- External Libraries -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<!-- ========================================================================
CSS STYLES - MATCHING STEP 8 STYLING
======================================================================== -->
<style>
/* GLOBAL RESET & BASE */
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f7fa; color: #333; line-height: 1.6; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
/* HEADER & PROGRESS BAR */
.header { text-align: center; margin-bottom: 30px; padding: 25px; background: linear-gradient(135deg, #2c3e50, #4a6491); color: #fff; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,.1); }
.header h1 { font-size: 28px; margin-bottom: 10px; }
.header p { opacity: .9; font-size: 16px; }
.progress-container { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; position: relative; max-width: 100%; }
.progress-container::before { content: ""; position: absolute; top: 50%; left: 0; right: 0; height: 4px; background: #e0e0e0; transform: translateY(-50%); z-index: 1; }
.progress-bar { position: absolute; top: 50%; left: 0; height: 4px; background: #1abc9c; transform: translateY(-50%); z-index: 2; transition: width .3s ease; width: 90%; }
.step { display: flex; flex-direction: column; align-items: center; position: relative; z-index: 3; width: 100px; }
.step span:first-child { width: 40px; height: 40px; border-radius: 50%; background: #e0e0e0; color: #666; display: flex; align-items: center; justify-content: center; font-weight: 700; margin-bottom: 8px; border: 3px solid #fff; transition: all .3s ease; }
.step.completed span:first-child { background: #2ecc71; color: #fff; }
.step.active span:first-child { background: #1abc9c; color: #fff; transform: scale(1.1); }
.step-label { font-size: 12px; text-align: center; color: #666; font-weight: 500; max-width: 100px; word-wrap: break-word; }
.step.completed .step-label { color: #2ecc71; }
.step.active .step-label { color: #1abc9c; font-weight: 600; }
/* FORM CONTAINER & GRID */
.form-container { background: #fff; border-radius: 10px; border-left: 4px solid #1abc9c; padding: 30px; box-shadow: 0 5px 20px rgba(0,0,0,.08); margin-bottom: 30px; }
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 20px; }
.form-group { display: flex; flex-direction: column; }
.form-group.full-width { grid-column: 1 / -1; }
label { margin-bottom: 8px; font-weight: 600; color: #2c3e50; font-size: 14px; }
input[type="text"], input[type="email"], input[type="number"], select, textarea { padding: 12px 15px; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 15px; transition: all .3s ease; background: #fff; width: 100%; }
input[type="text"]:focus, input[type="email"]:focus, input[type="number"]:focus, select:focus, textarea:focus { outline: none; border-color: #1abc9c; box-shadow: 0 0 0 3px rgba(26, 188, 156, 0.1); }
input[readonly] { background: #f8f9fa; border-color: #ddd; color: #666; font-weight: 600; }
.required::after { content: " *"; color: #e74c3c; }
.helper-text { font-size: 12px; color: #7f8c8d; margin-top: 5px; }
/* ALERTS & MESSAGES */
.alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; text-align: center; font-weight: 500; }
.alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
.warning-message { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin-bottom: 20px; border-radius: 4px; color: #856404; }
.warning-message i { color: #ffc107; margin-right: 10px; }
/* SECTIONS & TITLES */
.section-title { font-size: 18px; color: #2c3e50; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 2px solid #1abc9c; display: flex; align-items: center; gap: 10px; }
.section-title i { color: #1abc9c; }
.school-info { background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #1abc9c; }
.school-info h3 { color: #2c3e50; margin-bottom: 10px; font-size: 16px; }
.school-info p { color: #666; font-size: 14px; }
.info-box { background: #e8f6f3; border-left: 4px solid #1abc9c; padding: 20px; margin-bottom: 25px; border-radius: 8px; }
.info-box h4 { color: #16a085; margin-bottom: 10px; font-size: 16px; display: flex; align-items: center; gap: 8px; }
.info-box p { color: #555; font-size: 14px; line-height: 1.6; }
.input-with-icon { position: relative; }
.input-icon { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #7f8c8d; z-index: 2; }
.input-with-icon input, .input-with-icon select { padding-left: 45px; }
/* BUTTONS & NAVIGATION */
.navigation-buttons { display: flex; justify-content: space-between; margin-top: 40px; padding-top: 20px; border-top: 1px solid #eee; }
.nav-btn { padding: 12px 30px; background: linear-gradient(135deg, #1abc9c, #16a085); color: #fff; border: none; border-radius: 6px; font-size: 16px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 10px; transition: all .3s ease; }
.nav-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 15px rgba(26, 188, 156, 0.3); }
.nav-btn.back { background: linear-gradient(135deg, #7f8c8d, #95a5a6); }
.nav-btn:disabled { background: #95a5a6; cursor: not-allowed; opacity: .7; }
.loading-spinner { display: inline-block; width: 20px; height: 20px; border: 3px solid rgba(255,255,255,.3); border-radius: 50%; border-top-color: #fff; animation: spin 1s ease-in-out infinite; margin-right: 10px; }
@keyframes spin { to { transform: rotate(360deg); } }
/* CONDITIONAL SECTIONS */
.conditional-section { background-color: #f8f9fa; padding: 25px; border-radius: 8px; border-left: 4px solid #1abc9c; margin-top: 20px; display: none; animation: fadeIn 0.3s ease; }
.conditional-section.active { display: block; }
.bank-details-section { background-color: #e8f4fc; padding: 20px; border-radius: 8px; margin-top: 20px; border-left: 4px solid #1abc9c; display: none; animation: slideDown 0.3s ease; }
.bank-details-section.active { display: block; }
.no-smc-section { background-color: #fdeaea; padding: 25px; border-radius: 8px; border-left: 4px solid #e74c3c; margin-top: 20px; display: none; animation: fadeIn 0.3s ease; }
.no-smc-section.active { display: block; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
.radio-group { display: flex; gap: 30px; margin-bottom: 20px; }
.radio-option { display: flex; align-items: center; gap: 8px; cursor: pointer; }
.radio-option input[type="radio"] { width: 18px; height: 18px; cursor: pointer; }
.radio-label { font-weight: 600; color: #2c3e50; cursor: pointer; }
/* CHARACTER COUNTER */
.character-counter {
    font-size: 12px;
    margin-top: 5px;
    text-align: right;
}
.character-counter .count {
    font-weight: 600;
}
.character-counter .count.normal { color: #27ae60; }
.character-counter .count.warning { color: #f39c12; }
.character-counter .count.danger { color: #e74c3c; }
.character-counter .required-length {
    color: #7f8c8d;
}
/* VALIDATION STYLES */
.validation-error { border-color: #e74c3c !important; background-color: #fff8f8 !important; }
.error-text { color: #e74c3c; font-size: 12px; margin-top: 5px; display: none; }
.error-text.show { display: block; }
/* RESPONSIVE DESIGN */
@media (max-width: 992px) { .budget-wrapper { grid-template-columns: 1fr; } }
@media (max-width: 768px) {
.form-grid { grid-template-columns: 1fr; }
.progress-container { overflow-x: auto; padding-bottom: 20px; }
.step { width: 60px; }
.step-label { font-size: 10px; }
.radio-group { flex-direction: column; gap: 15px; }
}
@media (max-width: 480px) {
.container { padding: 10px; }
.form-container { padding: 15px; }
.header { padding: 15px; }
.nav-btn { padding: 10px 15px; font-size: 14px; }
}
/* BADGES */
.fy-badge { display: inline-block; background: #1abc9c; color: #fff; padding: 5px 15px; border-radius: 50px; font-weight: 700; margin-left: 15px; font-size: 14px; }
</style>
</head>
<body>
<?php include 'floating_logout_school.php'; ?>
<div class="container">
<!-- Header -->
<div class="header">
<h1><i class="fas fa-users-cog"></i> School Management Committee Registration - Step 9 of 10</h1>
<p>Complete all 10 steps to register a new school in Districts Schools Management System</p>
</div>
<!-- Progress Bar -->
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
<?php
$labels = ['Profile','Land','Building','Facilities','Posts','Students','Results','Budget','SMC','Location'];
for($i=1; $i<=10; $i++):
?>
<div class="step <?php echo $i<9?'completed':($i==9?'active':''); ?>" id="step<?php echo $i; ?>">
<span><?php echo $i; ?></span>
<span class="step-label"><?php echo $labels[$i-1]; ?></span>
</div>
<?php endfor; ?>
</div>
<!-- Messages -->
<?php if(!empty($success_message)): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?></div>
<?php endif; ?>
<?php if(!empty($error_message)): ?>
<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error_message); ?></div>
<?php endif; ?>
<!-- Main Form Container -->
<div class="form-container">
<div class="school-info">
<h3><i class="fas fa-info-circle"></i> SMC Information</h3>
<p>Fill in School Management Committee details for <strong><?php echo htmlspecialchars($school_name); ?></strong>
(EMIS: <strong><?php echo htmlspecialchars($emis_code); ?></strong>).
Fields marked with <span style="color:#e74c3c">*</span> are compulsory based on your selection.</p>
</div>
<div class="info-box">
<h4><i class="fas fa-info-circle"></i> About School Management Committee (SMC)</h4>
<p>The School Management Committee (SMC) plays a vital role in school governance, involving parents, teachers, and community members in decision-making processes. SMC helps in school development, monitoring, and resource management.</p>
</div>
<form method="POST" action="school_step9_save.php" id="smcForm">
<!-- Hidden Fields -->
<input type="hidden" name="emis_code" value="<?php echo htmlspecialchars($emis_code); ?>">
<input type="hidden" name="school_name" value="<?php echo htmlspecialchars($school_name); ?>">

<!-- SECTION 1: SMC Availability -->
<div class="form-section">
<h3 class="section-title"><i class="fas fa-check-circle"></i> SMC Availability</h3>
<div class="form-group full-width">
<label class="required">Does the school have a School Management Committee (SMC)?</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="smc_yes" name="smc_select" value="yes" <?php echo ($form_data['smc_select'] ?? '') == 'yes' ? 'checked' : ''; ?> required>
<label for="smc_yes" class="radio-label">Yes, we have an SMC</label>
</div>
<div class="radio-option">
<input type="radio" id="smc_no" name="smc_select" value="no" <?php echo ($form_data['smc_select'] ?? '') == 'no' ? 'checked' : ''; ?>>
<label for="smc_no" class="radio-label">No, we don't have an SMC</label>
</div>
</div>
<p class="helper-text">Select whether your school has an active School Management Committee</p>
<div class="error-text" id="smc_select_error">Please select whether the school has an SMC</div>
</div>
</div>

<!-- SECTION 2: SMC Details (Conditional - When Yes is selected) -->
<div id="smcDetailsSection" class="conditional-section" style="<?php echo ($form_data['smc_select'] ?? '') == 'yes' ? 'display: block;' : 'display: none;'; ?>">
<h3 class="section-title"><i class="fas fa-clipboard-list"></i> SMC Committee Details</h3>
<div class="form-grid">
<div class="form-group">
<label for="smcactive" class="required">Is the SMC active?</label>
<select id="smcactive" name="smcactive">
<option value="">Select Status...</option>
<option value="Yes" <?php echo ($form_data['smcactive'] ?? '') == 'Yes' ? 'selected' : ''; ?>>Yes, active</option>
<option value="No" <?php echo ($form_data['smcactive'] ?? '') == 'No' ? 'selected' : ''; ?>>No, not active</option>
</select>
<div class="error-text" id="smcactive_error">Please select SMC active status</div>
</div>
<div class="form-group">
<label for="smctraining" class="required">Has SMC received training?</label>
<select id="smctraining" name="smctraining">
<option value="">Select Status...</option>
<option value="Yes" <?php echo ($form_data['smctraining'] ?? '') == 'Yes' ? 'selected' : ''; ?>>Yes, received training</option>
<option value="No" <?php echo ($form_data['smctraining'] ?? '') == 'No' ? 'selected' : ''; ?>>No training received</option>
</select>
<div class="error-text" id="smctraining_error">Please select SMC training status</div>
</div>
</div>
<div class="form-grid">
<div class="form-group">
<label for="smcp">SMC President Name</label>
<div class="input-with-icon">
<i class="fas fa-user input-icon"></i>
<input id="smcp" name="smcp" type="text" 
       placeholder="Enter president's full name"
       value="<?php echo htmlspecialchars($form_data['smcp'] ?? ''); ?>">
</div>
</div>
<div class="form-group">
<label for="smcpc">President Contact Number</label>
<div class="input-with-icon" style="display: flex; align-items: center;">
    <i class="fas fa-phone input-icon" style="left: 15px;"></i>
    <span style="position: absolute; left: 45px; top: 50%; transform: translateY(-50%); color: #666; font-weight: 600; z-index: 2; background: #f0f0f0; padding: 2px 5px; border-radius: 3px;">+92</span>
    <input id="smcpc" name="smcpc" type="text" 
           placeholder="3001234567"
           style="padding-left: 85px !important;"
           maxlength="10"
           value="<?php 
                $phone = $form_data['smcpc'] ?? '';
                // Remove +92 if present for display
                if (strpos($phone, '+92') === 0) {
                    echo htmlspecialchars(substr($phone, 3));
                } else {
                    echo htmlspecialchars($phone);
                }
           ?>">
</div>
<p class="helper-text">Enter 10 digits after +92 (e.g., 3001234567) - Do not start with 0</p>
<div class="error-text" id="smcpc_error">Please enter a valid 10-digit Pakistan phone number (no leading zero)</div>
</div>
</div>
<div class="form-group">
<label for="smcbankaccount" class="required">Does SMC have a bank account?</label>
<select id="smcbankaccount" name="smcbankaccount">
<option value="">Select Option...</option>
<option value="Yes" <?php echo ($form_data['smcbankaccount'] ?? '') == 'Yes' ? 'selected' : ''; ?>>Yes, has bank account</option>
<option value="No" <?php echo ($form_data['smcbankaccount'] ?? '') == 'No' ? 'selected' : ''; ?>>No bank account</option>
</select>
<div class="error-text" id="smcbankaccount_error">Please select bank account status</div>
</div>
<!-- Bank Details Section (Conditional) -->
<div id="bankDetailsSection" class="bank-details-section" style="<?php echo ($form_data['smcbankaccount'] ?? '') == 'Yes' ? 'display: block;' : 'display: none;'; ?>">
<h4 class="section-title"><i class="fas fa-university"></i> Bank Account Details</h4>
<div class="form-grid">
<div class="form-group">
<label for="smcbankname" class="required">Bank Name</label>
<div class="input-with-icon">
<i class="fas fa-landmark input-icon"></i>
<input id="smcbankname" name="smcbankname" type="text" 
       placeholder="e.g., National Bank of Pakistan"
       value="<?php echo htmlspecialchars($form_data['smcbankname'] ?? ''); ?>">
</div>
<div class="error-text" id="smcbankname_error">Please enter bank name</div>
</div>
<div class="form-group">
<label for="smcbac" class="required">Account Number</label>
<div class="input-with-icon">
<i class="fas fa-credit-card input-icon"></i>
<input id="smcbac" name="smcbac" type="text" 
       placeholder="Enter account number"
       value="<?php echo htmlspecialchars($form_data['smcbac'] ?? ''); ?>">
</div>
<div class="error-text" id="smcbac_error">Please enter account number</div>
</div>
</div>
<div class="form-group">
<label for="smcamount">Amount Received This Year (PKR)</label>
<div class="input-with-icon">
<i class="fas fa-money-bill-wave input-icon"></i>
<input id="smcamount" name="smcamount" type="number" 
       min="0"
       placeholder="Enter amount in Pakistani Rupees"
       value="<?php echo htmlspecialchars($form_data['smcamount'] ?? ''); ?>">
</div>
<p class="helper-text">Total funds received by SMC in current fiscal year</p>
</div>
</div>
</div>

<!-- SECTION 3: No SMC Reason (Conditional - When No is selected) -->
<div id="noSMCsection" class="no-smc-section" style="<?php echo ($form_data['smc_select'] ?? '') == 'no' ? 'display: block;' : 'display: none;'; ?>">
    <h3 class="section-title"><i class="fas fa-exclamation-triangle"></i> Reason for No SMC</h3>
    <div class="form-group full-width">
        <label for="nosmc" class="required">Please explain why the school doesn't have an SMC (minimum 50 characters)</label>
        <textarea id="nosmc" name="nosmc" 
                  placeholder="Explain the reason in detail (e.g., School is new, awaiting formation, not required, etc.)"
                  rows="4" minlength="50"><?php echo htmlspecialchars($form_data['nosmc'] ?? ''); ?></textarea>
        <div class="character-counter">
            <span class="count <?php 
                $current_length = strlen($form_data['nosmc'] ?? '');
                if ($current_length >= 50) echo 'normal';
                elseif ($current_length >= 30) echo 'warning';
                else echo 'danger';
            ?>" id="nosmc_char_count"><?php echo strlen($form_data['nosmc'] ?? ''); ?></span>
            <span class="required-length">/ 50 characters minimum</span>
        </div>
        <p class="helper-text">Provide detailed explanation for not having an SMC. Minimum 50 characters required.</p>
        <div class="error-text" id="nosmc_error">Please provide a reason with at least 50 characters</div>
    </div>
</div>

<!-- Navigation Buttons -->
<div class="navigation-buttons">
    <button type="button" class="nav-btn back" onclick="window.location.href='school_step8.php'">
        <i class="fas fa-arrow-left"></i> Back
    </button>
    <button type="submit" class="nav-btn" id="submitBtn" name="school_smc_submit" value="1">
        <i class="fas fa-save"></i> Save & Continue
    </button>
</div>
</form>
</div>
</div>

<!-- ========================================================================
JAVASCRIPT - CONDITIONAL LOGIC & VALIDATION
======================================================================== -->
<script>
$(document).ready(function() {
    
    // SMC availability radio buttons
    $('#smc_yes, #smc_no').on('change', function() {
        if ($('#smc_yes').is(':checked')) {
            $('#smcDetailsSection').addClass('active').slideDown();
            $('#noSMCsection').removeClass('active').slideUp();
            // Set required attributes for SMC fields
            $('#smcactive, #smctraining, #smcbankaccount').attr('required', true);
            $('#nosmc').removeAttr('required').val('');
        } else if ($('#smc_no').is(':checked')) {
            $('#noSMCsection').addClass('active').slideDown();
            $('#smcDetailsSection').removeClass('active').slideUp();
            // Set required for no SMC reason
            $('#nosmc').attr('required', true);
            $('#smcactive, #smctraining, #smcbankaccount').removeAttr('required').val('');
            $('#bankDetailsSection').removeClass('active').slideUp();
        }
    });

    // Bank account toggle
    $('#smcbankaccount').on('change', function() {
        if ($(this).val() === 'Yes') {
            $('#bankDetailsSection').addClass('active').slideDown();
            $('#smcbankname, #smcbac').attr('required', true);
        } else {
            $('#bankDetailsSection').removeClass('active').slideUp();
            $('#smcbankname, #smcbac').removeAttr('required').val('');
            $('#smcamount').val('');
        }
    });

    // Phone number handling - only allow 10 digits, no leading zero
    $('#smcpc').on('input', function() {
        // Remove any non-digit characters
        let digits = $(this).val().replace(/\D/g, '');
        
        // Remove leading zero if present
        if (digits.length > 0 && digits.charAt(0) === '0') {
            digits = digits.substring(1);
        }
        
        // Limit to 10 digits
        if (digits.length > 10) {
            digits = digits.substr(0, 10);
        }
        
        $(this).val(digits);
    });

    // Validate phone number on blur (10 digits, no leading zero)
    $('#smcpc').on('blur', function() {
        const digits = $(this).val();
        if (digits) {
            if (!/^[1-9]\d{9}$/.test(digits)) {
                $(this).addClass('validation-error');
                $('#smcpc_error').text('Please enter exactly 10 digits starting with 3-9 (no leading zero)').addClass('show');
            } else {
                $(this).removeClass('validation-error').css('border-color', '#2ecc71');
                $('#smcpc_error').removeClass('show');
            }
        } else {
            $(this).removeClass('validation-error');
            $('#smcpc_error').removeClass('show');
        }
    });

    // Character counter for no SMC reason
    $('#nosmc').on('input', function() {
        const text = $(this).val();
        const count = text.length;
        const countSpan = $('#nosmc_char_count');
        
        countSpan.text(count);
        
        if (count >= 50) {
            countSpan.removeClass('warning danger').addClass('normal');
            $(this).css('border-color', '#2ecc71');
        } else if (count >= 30) {
            countSpan.removeClass('normal danger').addClass('warning');
            $(this).css('border-color', '#f39c12');
        } else {
            countSpan.removeClass('normal warning').addClass('danger');
            if (count > 0) {
                $(this).css('border-color', '#e74c3c');
            }
        }
    });

    // Clear validation errors on input
    $('input, select, textarea').on('input change', function() {
        $(this).removeClass('validation-error');
        const errorId = $(this).attr('id') + '_error';
        $('#' + errorId).removeClass('show');
    });

    // Real-time validation feedback
    $('input[required], select[required], textarea[required]').on('blur', function() {
        if ($(this).val()) {
            $(this).css('border-color', '#2ecc71');
        } else {
            $(this).css('border-color', '#e74c3c');
        }
    });

    // === COMPULSORY FIELD VALIDATION ===
    function validateCompulsoryFields() {
        let isValid = true;
        
        // Clear previous error styling
        $('.validation-error').removeClass('validation-error');
        $('.error-text').removeClass('show');
        
        // Check if SMC availability is selected
        if (!$('#smc_yes').is(':checked') && !$('#smc_no').is(':checked')) {
            isValid = false;
            $('#smc_select_error').addClass('show');
        }
        
        // Validate based on selection
        if ($('#smc_yes').is(':checked')) {
            // Validate SMC active status
            if (!$('#smcactive').val()) {
                isValid = false;
                $('#smcactive').addClass('validation-error');
                $('#smcactive_error').addClass('show');
            }
            
            // Validate SMC training status
            if (!$('#smctraining').val()) {
                isValid = false;
                $('#smctraining').addClass('validation-error');
                $('#smctraining_error').addClass('show');
            }
            
            // Validate bank account status
            if (!$('#smcbankaccount').val()) {
                isValid = false;
                $('#smcbankaccount').addClass('validation-error');
                $('#smcbankaccount_error').addClass('show');
            }
            
            // If bank account is Yes, validate bank details
            if ($('#smcbankaccount').val() === 'Yes') {
                if (!$('#smcbankname').val()) {
                    isValid = false;
                    $('#smcbankname').addClass('validation-error');
                    $('#smcbankname_error').addClass('show');
                }
                if (!$('#smcbac').val()) {
                    isValid = false;
                    $('#smcbac').addClass('validation-error');
                    $('#smcbac_error').addClass('show');
                }
            }
            
            // Validate phone number if provided (10 digits, no leading zero)
            const phoneDigits = $('#smcpc').val();
            if (phoneDigits) {
                if (!/^[1-9]\d{9}$/.test(phoneDigits)) {
                    isValid = false;
                    $('#smcpc').addClass('validation-error');
                    $('#smcpc_error').text('Please enter exactly 10 digits starting with 3-9 (no leading zero)').addClass('show');
                }
            }
            
        } else if ($('#smc_no').is(':checked')) {
            // Validate no SMC reason (minimum 50 characters)
            const reason = $('#nosmc').val().trim();
            if (reason.length < 50) {
                isValid = false;
                $('#nosmc').addClass('validation-error');
                $('#nosmc_error').addClass('show');
            }
        }
        
        return isValid;
    }

    // Form Submission Handler
    $('#smcForm').on('submit', function(e) {
        // Run validation
        if (!validateCompulsoryFields()) {
            e.preventDefault();
            $('#submitBtn').html('<i class="fas fa-save"></i> Save & Continue').prop('disabled', false);
            
            // Scroll to first error
            $('html, body').animate({ 
                scrollTop: $(".validation-error, .error-text.show").first().offset().top - 100 
            }, 1000);
            
            return false;
        }
        
        // Show loading state
        $('#submitBtn').html('<span class="loading-spinner"></span> Processing...').prop('disabled', true);
        // Form submits naturally
    });

    // Initial state check based on form data
    <?php if (!empty($form_data)): ?>
        if ($('#smc_yes').is(':checked')) {
            $('#smcDetailsSection').addClass('active').show();
            if ($('#smcbankaccount').val() === 'Yes') {
                $('#bankDetailsSection').addClass('active').show();
            }
        } else if ($('#smc_no').is(':checked')) {
            $('#noSMCsection').addClass('active').show();
            // Trigger character counter on page load
            setTimeout(function() {
                $('#nosmc').trigger('input');
            }, 100);
        }
    <?php endif; ?>
    
    console.log('SMC Form Loaded | EMIS: <?php echo $emis_code; ?>');
});
</script>
</body>
</html>