<?php
// Start session
require_once 'session_config_emp.php';

// Check if employee is logged in
if (!isset($_SESSION['employee_id']) || !isset($_SESSION['cnic'])) {
    header('Location: login_emp.php');
    exit();
}

include 'connect.php';

// Get employee data from session
$employee_id = $_SESSION['employee_id'];
$cnic = $_SESSION['cnic'];
$error = '';
$success = '';

// Initialize variables
$db_employee_id = null;
$boards = [];
$universities = [];
$is_edit = false;
$qualification_data = null;
$qualification_id = 0;

// Check if editing existing qualification
if (isset($_GET['qualification_id'])) {
    $qualification_id = intval($_GET['qualification_id']);
    $is_edit = ($qualification_id > 0);
}

// Get employee_id from database
$sql_reg = "SELECT emp_numb FROM registrations_emp WHERE id = ? AND cnic = ?";
$stmt_reg = $conn->prepare($sql_reg);
$stmt_reg->bind_param("is", $employee_id, $cnic);
$stmt_reg->execute();
$result_reg = $stmt_reg->get_result();

if ($result_reg->num_rows > 0) {
    $reg_data = $result_reg->fetch_assoc();
    $personal_no = $reg_data['emp_numb'];
    
    // Get employee_id from employees table
    $emp_sql = "SELECT employee_id FROM employees WHERE personal_no = ? LIMIT 1";
    $stmt_emp = $conn->prepare($emp_sql);
    $stmt_emp->bind_param("s", $personal_no);
    $stmt_emp->execute();
    $emp_result = $stmt_emp->get_result();
    
    if ($emp_result->num_rows > 0) {
        $employee_data = $emp_result->fetch_assoc();
        $db_employee_id = $employee_data['employee_id'];
        
        // If editing, fetch qualification data
        if ($is_edit) {
            $qual_sql = "SELECT * FROM professional_qualifications WHERE qualification_id = ? AND employee_id = ?";
            $stmt_qual = $conn->prepare($qual_sql);
            $stmt_qual->bind_param("ii", $qualification_id, $db_employee_id);
            $stmt_qual->execute();
            $qual_result = $stmt_qual->get_result();
            
            if ($qual_result->num_rows > 0) {
                $qualification_data = $qual_result->fetch_assoc();
            } else {
                $error = "Qualification not found or you don't have permission to edit it.";
                $is_edit = false;
            }
            $stmt_qual->close();
        }
        
        // Fetch boards and universities for dropdown
        $boards_sql = "SELECT b_id, b_name FROM boards ORDER BY b_name";
        $boards_result = $conn->query($boards_sql);
        if ($boards_result) {
            while($row = $boards_result->fetch_assoc()) {
                $boards[] = $row;
            }
        }
        
        $unis_sql = "SELECT uni_id, uni_name FROM universities ORDER BY uni_name";
        $unis_result = $conn->query($unis_sql);
        if ($unis_result) {
            while($row = $unis_result->fetch_assoc()) {
                $universities[] = $row;
            }
        }
        
        $stmt_emp->close();
    } else {
        $error = "Employee profile not found in main database.";
    }
} else {
    $error = "Registration record not found.";
}

$stmt_reg->close();

// Function to format date for display (dd/mm/yyyy)
function formatDateForDisplay($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return '';
    }
    
    $timestamp = strtotime($date);
    if ($timestamp === false) {
        return $date;
    }
    
    return date('d/m/Y', $timestamp);
}

// Function to format date for MySQL (YYYY-MM-DD)
function formatDateForMySQL($date) {
    if (empty($date)) {
        return null;
    }
    
    // If already in YYYY-MM-DD format, return as is
    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
        return $date;
    }
    
    // If in dd/mm/yyyy format, convert to YYYY-MM-DD
    if (preg_match('/^(\d{2})\/(\d{2})\/(\d{4})$/', $date, $matches)) {
        return $matches[3] . '-' . $matches[2] . '-' . $matches[1];
    }
    
    // If in dd/mm/yy format, convert to YYYY-MM-DD
    if (preg_match('/^(\d{2})\/(\d{2})\/(\d{2})$/', $date, $matches)) {
        $year = $matches[3];
        // Convert 2-digit year to 4-digit (assuming years 00-69 are 2000-2069, 70-99 are 1970-1999)
        $year = ($year < 70) ? '20' . $year : '19' . $year;
        return $year . '-' . $matches[2] . '-' . $matches[1];
    }
    
    return null;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $db_employee_id) {
    $qualification_name = trim($_POST['qualification_name'] ?? '');
    $institution = trim($_POST['institution'] ?? '');
    $custom_institution = trim($_POST['custom_institution'] ?? '');
    $passing_date = trim($_POST['passing_date'] ?? '');
    $total_marks = floatval($_POST['total_marks'] ?? 0);
    $obtained_marks = floatval($_POST['obtained_marks'] ?? 0);
    $division_grade = trim($_POST['division_grade'] ?? '');
    
    // Use custom institution if provided, otherwise use selected institution
    $final_institution = !empty($custom_institution) ? $custom_institution : $institution;
    
    // Format date for MySQL
    $mysql_date = formatDateForMySQL($passing_date);
    
    // Validation
    if (empty($qualification_name)) {
        $error = "Qualification name is required.";
    } elseif (empty($final_institution)) {
        $error = "Institution is required.";
    } elseif (empty($passing_date)) {
        $error = "Passing date is required.";
    } elseif (!$mysql_date) {
        $error = "Invalid date format. Please use dd/mm/yyyy or dd/mm/yy format.";
    } elseif ($total_marks < 0 || $obtained_marks < 0) {
        $error = "Marks cannot be negative.";
    } elseif ($obtained_marks > $total_marks) {
        $error = "Obtained marks cannot be greater than total marks.";
    } else {
        if ($is_edit && $qualification_data) {
            // Update existing qualification
            $update_sql = "UPDATE professional_qualifications SET 
                          qualification_name = ?,
                          institution = ?,
                          passing_year = ?,
                          total_marks = ?,
                          obtained_marks = ?,
                          division_grade = ?
                          WHERE qualification_id = ? AND employee_id = ?";
            
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("sssddssi", 
                $qualification_name,
                $final_institution,
                $mysql_date,
                $total_marks,
                $obtained_marks,
                $division_grade,
                $qualification_id,
                $db_employee_id
            );
        } else {
            // Insert new qualification
            $insert_sql = "INSERT INTO professional_qualifications 
                          (employee_id, qualification_name, institution, passing_year, total_marks, obtained_marks, division_grade)
                          VALUES (?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("isssdds",
                $db_employee_id,
                $qualification_name,
                $final_institution,
                $mysql_date,
                $total_marks,
                $obtained_marks,
                $division_grade
            );
        }
        
        if ($stmt->execute()) {
            $success = $is_edit ? 
                "Professional qualification updated successfully!" : 
                "Professional qualification added successfully!";
            
            // Redirect after success
            $_SESSION['success_message'] = $success;
            header("Location: professional_qualification_view.php");
            exit();
        } else {
            $error = "Failed to save qualification. Please try again. Error: " . $conn->error;
        }
        $stmt->close();
    }
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $is_edit ? 'Edit' : 'Add'; ?> Professional Qualification</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    :root {
        --primary-info: #0dcaf0;
        --secondary-info: #31d2f2;
    }
    
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: #f8f9fa;
        padding: 20px;
    }
    
    .edit-container {
        max-width: 800px;
        margin: 0 auto;
    }
    
    .edit-card {
        border: none;
        border-radius: 15px;
        box-shadow: 0 5px 25px rgba(0,0,0,0.1);
        background: white;
        overflow: hidden;
    }
    
    .edit-header {
        background: linear-gradient(135deg, #0dcaf0 0%, #0d6efd 100%);
        color: white;
        padding: 25px 30px;
    }
    
    .form-card {
        background: #f8fafc;
        border-radius: 10px;
        padding: 25px;
        margin-bottom: 20px;
        border: 1px solid #e9ecef;
    }
    
    .form-section-title {
        font-weight: 600;
        color: var(--primary-info);
        margin-bottom: 20px;
        font-size: 1.1rem;
        display: flex;
        align-items: center;
        gap: 10px;
        padding-bottom: 10px;
        border-bottom: 2px solid #e9ecef;
    }
    
    .btn-submit {
        background: var(--primary-info);
        color: white;
        border: none;
        padding: 12px 30px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
        font-size: 1rem;
    }
    
    .btn-submit:hover {
        background: var(--secondary-info);
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(13, 202, 240, 0.3);
    }
    
    .btn-cancel {
        background: #6c757d;
        color: white;
        border: none;
        padding: 12px 30px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
        font-size: 1rem;
    }
    
    .btn-cancel:hover {
        background: #5a6268;
        color: white;
        transform: translateY(-2px);
    }
    
    .required-label::after {
        content: " *";
        color: #dc3545;
    }
    
    .form-label {
        font-weight: 500;
        color: #495057;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: #0dcaf0;
        box-shadow: 0 0 0 0.25rem rgba(13, 202, 240, 0.25);
    }
    
    .percentage-display {
        background: #e7f5ff;
        border: 1px solid #a5d8ff;
        border-radius: 5px;
        padding: 10px 15px;
        margin-top: 10px;
        font-weight: 500;
    }
    
    .institution-section {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid #dee2e6;
    }
    
    .date-format {
        font-size: 0.85rem;
        color: #6c757d;
        margin-top: 5px;
    }
</style>
</head>
<body>
<div class="edit-container">
    <div class="edit-card">
        <div class="edit-header">
            <h2 class="mb-0">
                <i class="fas fa-certificate me-2"></i>
                <?php echo $is_edit ? 'Edit Professional Qualification' : 'Add Professional Qualification'; ?>
            </h2>
            <p class="mb-0 mt-2">
                <?php echo $is_edit ? 
                    'Update your professional qualification details' : 
                    'Add new professional certification or qualification'; ?>
            </p>
        </div>
        
        <div class="p-4">
            <?php if(!empty($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if($db_employee_id): ?>
                <form method="POST" action="" id="qualificationForm">
                    <div class="form-card">
                        <h5 class="form-section-title">
                            <i class="fas fa-info-circle"></i>Qualification Details
                        </h5>
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label for="qualification_name" class="form-label required-label">Qualification Name</label>
                                <input type="text" class="form-control" id="qualification_name" name="qualification_name" 
                                       value="<?php echo htmlspecialchars($qualification_data['qualification_name'] ?? ''); ?>" 
                                       required placeholder="e.g., Certified Public Accountant, Project Management Professional">
                                <div class="form-text">Enter the full name of your professional qualification</div>
                            </div>
                        </div>
                        
                        <!-- INSTITUTION SELECTION -->
                        <div class="institution-section">
                            <label class="form-label required-label mb-3">Institution/Board</label>
                            
                            <!-- Boards Dropdown -->
                            <div class="mb-3">
                                <label class="form-label">Select from Boards:</label>
                                <select class="form-select" id="board_select" onchange="updateInstitution()">
                                    <option value="">Select Board</option>
                                    <?php foreach($boards as $board): 
                                        $selected = (isset($qualification_data['institution']) && $qualification_data['institution'] == 'Board' . $board['b_id']) ? 'selected' : '';
                                    ?>
                                        <option value="Board<?php echo $board['b_id']; ?>" <?php echo $selected; ?>>
                                            <?php echo htmlspecialchars($board['b_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <!-- Universities Dropdown -->
                            <div class="mb-3">
                                <label class="form-label">Select from Universities:</label>
                                <select class="form-select" id="uni_select" onchange="updateInstitution()">
                                    <option value="">Select University</option>
                                    <?php foreach($universities as $uni): 
                                        $selected = (isset($qualification_data['institution']) && $qualification_data['institution'] == 'Uni' . $uni['uni_id']) ? 'selected' : '';
                                    ?>
                                        <option value="Uni<?php echo $uni['uni_id']; ?>" <?php echo $selected; ?>>
                                            <?php echo htmlspecialchars($uni['uni_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <!-- Custom Institution -->
                            <div class="mb-3">
                                <label class="form-label">Or enter custom institution:</label>
                                <input type="text" class="form-control" id="custom_institution" name="custom_institution" 
                                       value="<?php echo (isset($qualification_data['institution']) && 
                                               !str_starts_with($qualification_data['institution'], 'Board') && 
                                               !str_starts_with($qualification_data['institution'], 'Uni')) ? 
                                               htmlspecialchars($qualification_data['institution']) : ''; ?>" 
                                       placeholder="e.g., Institute of Chartered Accountants, PMI"
                                       oninput="updateInstitution()">
                            </div>
                            
                            <!-- Hidden field for the actual institution value -->
                            <input type="hidden" id="institution" name="institution" value="<?php echo htmlspecialchars($qualification_data['institution'] ?? ''); ?>">
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="passing_date" class="form-label required-label">Completion Date</label>
                                <input type="text" class="form-control" id="passing_date" name="passing_date" 
                                       value="<?php echo !empty($qualification_data['passing_year']) ? 
                                               formatDateForDisplay($qualification_data['passing_year']) : ''; ?>" 
                                       required placeholder="dd/mm/yyyy or dd/mm/yy">
                                <div class="date-format">
                                    <i class="fas fa-info-circle"></i> Format: dd/mm/yyyy (e.g., 15/06/2023) or dd/mm/yy (e.g., 15/06/23)
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-card">
                        <h5 class="form-section-title">
                            <i class="fas fa-chart-bar"></i>Performance Details (Optional)
                        </h5>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="total_marks" class="form-label">Total Marks</label>
                                <input type="number" class="form-control" id="total_marks" name="total_marks" 
                                       value="<?php echo $qualification_data['total_marks'] ?? ''; ?>" 
                                       placeholder="e.g., 1000" step="0.01" min="0">
                            </div>
                            <div class="col-md-6">
                                <label for="obtained_marks" class="form-label">Obtained Marks</label>
                                <input type="number" class="form-control" id="obtained_marks" name="obtained_marks" 
                                       value="<?php echo $qualification_data['obtained_marks'] ?? ''; ?>" 
                                       placeholder="e.g., 850" step="0.01" min="0">
                            </div>
                        </div>
                        
                        <div id="percentageDisplay" class="percentage-display" style="display: none;">
                            Percentage: <span id="percentageValue">0</span>%
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label for="division_grade" class="form-label">Grade/Division</label>
                                <select class="form-select" id="division_grade" name="division_grade">
                                    <option value="">Select Grade/Division</option>
                                    <option value="A+ (Distinction)" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'A+ (Distinction)') ? 'selected' : ''; ?>>A+ (Distinction)</option>
                                    <option value="A (Excellent)" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'A (Excellent)') ? 'selected' : ''; ?>>A (Excellent)</option>
                                    <option value="B (Good)" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'B (Good)') ? 'selected' : ''; ?>>B (Good)</option>
                                    <option value="C (Average)" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'C (Average)') ? 'selected' : ''; ?>>C (Average)</option>
                                    <option value="D (Pass)" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'D (Pass)') ? 'selected' : ''; ?>>D (Pass)</option>
                                    <option value="F (Fail)" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'F (Fail)') ? 'selected' : ''; ?>>F (Fail)</option>
                                    <option value="Pass" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'Pass') ? 'selected' : ''; ?>>Pass</option>
                                    <option value="Fail" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'Fail') ? 'selected' : ''; ?>>Fail</option>
                                    <option value="Not Graded" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'Not Graded') ? 'selected' : ''; ?>>Not Graded</option>
                                </select>
                                <div class="form-text">Select or enter custom grade (e.g., "Certified", "Completed")</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center mt-4">
                        <a href="professional_qualification_view.php" class="btn btn-cancel">
                            <i class="fas fa-times me-2"></i>Cancel
                        </a>
                        <button type="submit" class="btn btn-submit">
                            <i class="fas fa-save me-2"></i>
                            <?php echo $is_edit ? 'Update Qualification' : 'Add Qualification'; ?>
                        </button>
                    </div>
                </form>
            <?php elseif(!empty($error)): ?>
                <div class="alert alert-warning">
                    <h4><i class="fas fa-exclamation-triangle me-2"></i>Profile Not Found</h4>
                    <p><?php echo htmlspecialchars($error); ?></p>
                    <p>Please contact the administrator to complete your profile setup.</p>
                    <div class="mt-3">
                        <a href="employee_profile_view.php" class="btn btn-primary">
                            <i class="fas fa-arrow-left me-2"></i>Back to Profile
                        </a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    // Update institution value based on selection
    function updateInstitution() {
        const boardSelect = document.getElementById('board_select');
        const uniSelect = document.getElementById('uni_select');
        const customInstitution = document.getElementById('custom_institution');
        const institutionField = document.getElementById('institution');
        
        // Reset other selections when one is made
        if (boardSelect.value) {
            uniSelect.value = '';
            customInstitution.value = '';
            institutionField.value = boardSelect.value;
        } else if (uniSelect.value) {
            boardSelect.value = '';
            customInstitution.value = '';
            institutionField.value = uniSelect.value;
        } else if (customInstitution.value.trim()) {
            boardSelect.value = '';
            uniSelect.value = '';
            institutionField.value = customInstitution.value.trim();
        } else {
            institutionField.value = '';
        }
    }
    
    // Initialize institution selection
    function initializeInstitution() {
        const currentInstitution = document.getElementById('institution').value;
        const boardSelect = document.getElementById('board_select');
        const uniSelect = document.getElementById('uni_select');
        const customInstitution = document.getElementById('custom_institution');
        
        // Clear all selections first
        boardSelect.value = '';
        uniSelect.value = '';
        customInstitution.value = '';
        
        // Set the appropriate selection based on saved value
        if (currentInstitution) {
            if (currentInstitution.startsWith('Board')) {
                boardSelect.value = currentInstitution;
            } else if (currentInstitution.startsWith('Uni')) {
                uniSelect.value = currentInstitution;
            } else {
                customInstitution.value = currentInstitution;
            }
        }
    }
    
    // Calculate percentage
    function calculatePercentage() {
        const totalMarks = parseFloat(document.getElementById('total_marks').value) || 0;
        const obtainedMarks = parseFloat(document.getElementById('obtained_marks').value) || 0;
        
        if (totalMarks > 0 && obtainedMarks > 0) {
            const percentage = (obtainedMarks / totalMarks) * 100;
            document.getElementById('percentageValue').textContent = percentage.toFixed(2);
            document.getElementById('percentageDisplay').style.display = 'block';
            
            // Suggest grade based on percentage
            const gradeSelect = document.getElementById('division_grade');
            if (!gradeSelect.value) {
                if (percentage >= 80) {
                    gradeSelect.value = 'A+ (Distinction)';
                } else if (percentage >= 70) {
                    gradeSelect.value = 'A (Excellent)';
                } else if (percentage >= 60) {
                    gradeSelect.value = 'B (Good)';
                } else if (percentage >= 50) {
                    gradeSelect.value = 'C (Average)';
                } else if (percentage >= 40) {
                    gradeSelect.value = 'D (Pass)';
                }
            }
        } else {
            document.getElementById('percentageDisplay').style.display = 'none';
        }
    }
    
    // Date validation helper
    function isValidDate(dateString) {
        // Check if date matches dd/mm/yyyy or dd/mm/yy format
        const regex = /^(\d{1,2})\/(\d{1,2})\/(\d{4}|\d{2})$/;
        if (!regex.test(dateString)) {
            return false;
        }
        
        const parts = dateString.split('/');
        const day = parseInt(parts[0], 10);
        const month = parseInt(parts[1], 10);
        let year = parseInt(parts[2], 10);
        
        // Convert 2-digit year to 4-digit
        if (year < 100) {
            year = year < 70 ? 2000 + year : 1900 + year;
        }
        
        // Check month range
        if (month < 1 || month > 12) {
            return false;
        }
        
        // Check day range based on month
        const daysInMonth = [31, (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        
        if (day < 1 || day > daysInMonth[month - 1]) {
            return false;
        }
        
        return true;
    }
    
    // Format date as user types
    $(document).ready(function() {
        $('#passing_date').on('input', function() {
            let value = $(this).val().replace(/\D/g, '');
            
            if (value.length > 2) {
                value = value.substring(0, 2) + '/' + value.substring(2);
            }
            if (value.length > 5) {
                value = value.substring(0, 5) + '/' + value.substring(5, 9);
            }
            
            $(this).val(value);
        });
    });
    
    // Event listeners
    document.getElementById('total_marks').addEventListener('input', calculatePercentage);
    document.getElementById('obtained_marks').addEventListener('input', calculatePercentage);
    
    // Form validation
    document.getElementById('qualificationForm').addEventListener('submit', function(e) {
        const totalMarks = parseFloat(document.getElementById('total_marks').value) || 0;
        const obtainedMarks = parseFloat(document.getElementById('obtained_marks').value) || 0;
        const institution = document.getElementById('institution').value;
        const passingDate = document.getElementById('passing_date').value;
        
        if (!institution) {
            e.preventDefault();
            alert('Please select or enter an institution.');
            return false;
        }
        
        if (!passingDate) {
            e.preventDefault();
            alert('Please enter the completion date.');
            document.getElementById('passing_date').focus();
            return false;
        }
        
        if (!isValidDate(passingDate)) {
            e.preventDefault();
            alert('Invalid date format. Please use dd/mm/yyyy or dd/mm/yy format.');
            document.getElementById('passing_date').focus();
            return false;
        }
        
        if (totalMarks > 0 && obtainedMarks > totalMarks) {
            e.preventDefault();
            alert('Obtained marks cannot be greater than total marks.');
            document.getElementById('obtained_marks').focus();
            return false;
        }
        
        if (totalMarks < 0 || obtainedMarks < 0) {
            e.preventDefault();
            alert('Marks cannot be negative.');
            return false;
        }
    });
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        initializeInstitution();
        calculatePercentage();
    });
</script>
</body>
</html>