<?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 academic_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 convert dd/mm/yyyy to YYYY-MM-DD for MySQL
function convertToMySQLDate($date) {
    if (empty($date)) {
        return null;
    }
    
    // Remove any whitespace
    $date = trim($date);
    
    // Check if already in YYYY-MM-DD format
    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
        return $date;
    }
    
    // Handle dd/mm/yyyy format
    if (preg_match('/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/', $date, $matches)) {
        $day = str_pad($matches[1], 2, '0', STR_PAD_LEFT);
        $month = str_pad($matches[2], 2, '0', STR_PAD_LEFT);
        $year = $matches[3];
        return "$year-$month-$day";
    }
    
    return null;
}

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $db_employee_id) {
    $degree_type = trim($_POST['degree_type'] ?? '');
    $degree_name = trim($_POST['degree_name'] ?? '');
    $institution = trim($_POST['institution'] ?? '');
    $custom_institution = trim($_POST['custom_institution'] ?? '');
    $passing_date = trim($_POST['passing_date'] ?? '');
    $subjects = trim($_POST['subjects'] ?? '');
    $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;
    
    // Convert passing date to MySQL format
    $mysql_passing_date = convertToMySQLDate($passing_date);
    
    // Calculate percentage and division
    $percentage = ($total_marks > 0) ? ($obtained_marks / $total_marks) * 100 : 0;
    
    // Auto-calculate division if not provided
    if (empty($division_grade)) {
        if ($percentage >= 60) {
            $division_grade = '1st Division';
        } elseif ($percentage >= 45) {
            $division_grade = '2nd Division';
        } elseif ($percentage >= 33) {
            $division_grade = '3rd Division';
        } else {
            $division_grade = 'Failed';
        }
    }
    
    // Validation
    if (empty($degree_type)) {
        $error = "Degree type is required.";
    } elseif (empty($final_institution)) {
        $error = "Institution is required.";
    } elseif (empty($passing_date)) {
        $error = "Passing date is required.";
    } elseif (!$mysql_passing_date) {
        $error = "Invalid date format. Please use dd/mm/yyyy format (e.g., 15/06/2023).";
    } 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 academic_qualifications SET 
                          degree_type = ?,
                          degree_name = ?,
                          university_board = ?,
                          passing_year = ?,
                          subjects = ?,
                          total_marks = ?,
                          obtained_marks = ?,
                          division_grade = ?
                          WHERE qualification_id = ? AND employee_id = ?";
            
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("sssssddssi", 
                $degree_type,
                $degree_name,
                $final_institution,
                $mysql_passing_date,
                $subjects,
                $total_marks,
                $obtained_marks,
                $division_grade,
                $qualification_id,
                $db_employee_id
            );
        } else {
            // Insert new qualification
            $insert_sql = "INSERT INTO academic_qualifications 
                          (employee_id, degree_type, degree_name, university_board, passing_year, subjects, total_marks, obtained_marks, division_grade)
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("isssssdds",
                $db_employee_id,
                $degree_type,
                $degree_name,
                $final_institution,
                $mysql_passing_date,
                $subjects,
                $total_marks,
                $obtained_marks,
                $division_grade
            );
        }
        
        if ($stmt->execute()) {
            $success = $is_edit ? 
                "Academic qualification updated successfully!" : 
                "Academic qualification added successfully!";
            
            // Redirect after success
            $_SESSION['success_message'] = $success;
            header("Location: academic_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'; ?> Academic 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">
<!-- Add Flatpickr CSS for date picker -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<style>
    :root {
        --primary-green: #198754;
        --secondary-green: #157347;
    }
    
    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, #198754 0%, #0d6efd 100%);
        color: white;
        padding: 25px 30px;
    }
    
    .form-section {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        border-left: 4px solid var(--primary-green);
    }
    
    .section-title {
        font-weight: 600;
        color: var(--primary-green);
        margin-bottom: 20px;
        font-size: 1.1rem;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .btn-save {
        background: var(--primary-green);
        color: white;
        border: none;
        padding: 12px 30px;
        border-radius: 5px;
        font-weight: 500;
        transition: all 0.3s ease;
        font-size: 1rem;
    }
    
    .btn-save:hover {
        background: var(--secondary-green);
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(25, 135, 84, 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);
    }
    
    .form-control:focus, .form-select:focus {
        border-color: var(--primary-green);
        box-shadow: 0 0 0 0.25rem rgba(25, 135, 84, 0.25);
    }
    
    .required-label::after {
        content: " *";
        color: #dc3545;
    }
    
    .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;
    }
    
    .division-display {
        background: #e7f1ff;
        border-radius: 8px;
        padding: 15px;
        margin-top: 15px;
        border: 2px solid #0d6efd;
    }
    
    .division-value {
        font-size: 1.5rem;
        font-weight: 700;
        color: #0d6efd;
        text-align: center;
    }
    
    .percentage-value {
        font-size: 2rem;
        font-weight: 700;
        color: var(--primary-green);
        text-align: center;
    }
    
    .division-label {
        text-align: center;
        color: #6c757d;
        font-size: 0.9rem;
    }
    
    .division-1st {
        color: #198754;
    }
    
    .division-2nd {
        color: #ffc107;
    }
    
    .division-3rd {
        color: #dc3545;
    }
    
    .calculation-info {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 8px;
        padding: 10px;
        margin-top: 10px;
        font-size: 0.85rem;
    }
    
    .date-format-note {
        font-size: 0.85rem;
        color: #6c757d;
        margin-top: 5px;
        display: block;
    }
    
    .date-input-wrapper {
        position: relative;
    }
    
    .date-input-wrapper .form-control {
        padding-right: 40px;
    }
    
    .date-calendar-icon {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
        cursor: pointer;
        z-index: 10;
    }
    
    /* Custom Flatpickr styles */
    .flatpickr-calendar {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        border-radius: 10px;
        box-shadow: 0 5px 25px rgba(0,0,0,0.15);
        border: 1px solid #dee2e6;
    }
    
    .flatpickr-day.selected {
        background: var(--primary-green);
        border-color: var(--primary-green);
    }
    
    .flatpickr-day.today {
        border-color: var(--primary-green);
    }
    
    .flatpickr-day.today:hover {
        background: var(--primary-green);
        color: white;
    }
    
    .flatpickr-months .flatpickr-month {
        background: var(--primary-green);
        color: white;
        border-radius: 10px 10px 0 0;
    }
    
    .flatpickr-current-month .flatpickr-monthDropdown-months {
        background: transparent;
        color: white;
    }
    
    .flatpickr-current-month input.cur-year {
        color: white;
    }
    
    .flatpickr-weekdays {
        background: #f8f9fa;
    }
    
    .flatpickr-weekday {
        color: var(--primary-green);
        font-weight: 600;
    }
</style>
</head>
<body>
<div class="edit-container">
    <div class="edit-card">
        <div class="edit-header">
            <h2 class="mb-0">
                <i class="fas fa-graduation-cap me-2"></i>
                <?php echo $is_edit ? 'Edit' : 'Add'; ?> Academic Qualification
            </h2>
            <p class="mb-0 mt-2">
                <?php echo $is_edit ? 'Update your existing qualification' : 'Add a new academic 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">
                    <!-- DEGREE INFORMATION -->
                    <div class="form-section">
                        <h5 class="section-title">
                            <i class="fas fa-certificate"></i>Degree Information
                        </h5>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="degree_type" class="form-label required-label">Degree Type</label>
                                <select class="form-select" id="degree_type" name="degree_type" required>
                                    <option value="">Select Degree Type</option>
                                    <option value="Secondary" <?php echo (isset($qualification_data['degree_type']) && $qualification_data['degree_type'] == 'Secondary') ? 'selected' : ''; ?>>Secondary (Matric)</option>
                                    <option value="Higher Secondary" <?php echo (isset($qualification_data['degree_type']) && $qualification_data['degree_type'] == 'Higher Secondary') ? 'selected' : ''; ?>>Higher Secondary (Intermediate)</option>
                                    <option value="Bachelor" <?php echo (isset($qualification_data['degree_type']) && $qualification_data['degree_type'] == 'Bachelor') ? 'selected' : ''; ?>>Bachelor's Degree</option>
                                    <option value="Master" <?php echo (isset($qualification_data['degree_type']) && $qualification_data['degree_type'] == 'Master') ? 'selected' : ''; ?>>Master's Degree</option>
                                    <option value="M.Phil" <?php echo (isset($qualification_data['degree_type']) && $qualification_data['degree_type'] == 'M.Phil') ? 'selected' : ''; ?>>M.Phil</option>
                                    <option value="Ph.D" <?php echo (isset($qualification_data['degree_type']) && $qualification_data['degree_type'] == 'Ph.D') ? 'selected' : ''; ?>>Ph.D</option>
                                    <option value="Other" <?php echo (isset($qualification_data['degree_type']) && $qualification_data['degree_type'] == 'Other') ? 'selected' : ''; ?>>Other</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="degree_name" class="form-label">Degree Name</label>
                                <input type="text" class="form-control" id="degree_name" name="degree_name" 
                                       value="<?php echo htmlspecialchars($qualification_data['degree_name'] ?? ''); ?>" 
                                       placeholder="e.g., B.A., B.Sc., M.A., etc.">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="passing_date" class="form-label required-label">Passing Date</label>
                                <div class="date-input-wrapper">
                                    <input type="text" class="form-control" id="passing_date" name="passing_date" 
                                           value="<?php 
                                           if($is_edit && isset($qualification_data['passing_year'])) {
                                               echo formatDateForDisplay($qualification_data['passing_year']);
                                           } ?>" 
                                           required 
                                           placeholder="Click to select date">
                                    <i class="fas fa-calendar-alt date-calendar-icon" id="calendarTrigger"></i>
                                </div>
                                <span class="date-format-note">
                                    <i class="fas fa-info-circle"></i> Format: dd/mm/yyyy (e.g., 15/06/2023)
                                </span>
                            </div>
                            <div class="col-md-6">
                                <label for="subjects" class="form-label">Subjects</label>
                                <input type="text" class="form-control" id="subjects" name="subjects" 
                                       value="<?php echo htmlspecialchars($qualification_data['subjects'] ?? ''); ?>"
                                       placeholder="e.g., Mathematics, Physics, Computer Science">
                            </div>
                        </div>
                    </div>
                    
                    <!-- INSTITUTION INFORMATION -->
                    <div class="form-section">
                        <h5 class="section-title">
                            <i class="fas fa-university"></i>Institution Information
                        </h5>
                        
                        <!-- INSTITUTION SELECTION -->
                        <div class="institution-section">
                            <label class="form-label required-label mb-3">Board/University</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['university_board']) && 
                                                   $qualification_data['university_board'] == '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['university_board']) && 
                                                   $qualification_data['university_board'] == '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 
                                       if($is_edit && isset($qualification_data['university_board'])) {
                                           // Check if it's NOT a board or university ID format
                                           if (!preg_match('/^(Board|Uni)\d+$/', $qualification_data['university_board'])) {
                                               echo htmlspecialchars($qualification_data['university_board']);
                                           }
                                       } ?>" 
                                       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['university_board'] ?? ''); ?>">
                        </div>
                    </div>
                    
                    <!-- MARKS INFORMATION -->
                    <div class="form-section">
                        <h5 class="section-title">
                            <i class="fas fa-chart-bar"></i>Marks Information
                        </h5>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="total_marks" class="form-label required-label">Total Marks</label>
                                <input type="number" class="form-control" id="total_marks" name="total_marks" 
                                       value="<?php echo $qualification_data['total_marks'] ?? ''; ?>" 
                                       required min="1" step="0.01" 
                                       oninput="calculateDivision()">
                            </div>
                            <div class="col-md-6">
                                <label for="obtained_marks" class="form-label required-label">Obtained Marks</label>
                                <input type="number" class="form-control" id="obtained_marks" name="obtained_marks" 
                                       value="<?php echo $qualification_data['obtained_marks'] ?? ''; ?>" 
                                       required min="0" step="0.01" 
                                       oninput="calculateDivision()">
                            </div>
                        </div>
                        
                        <!-- DIVISION CALCULATION DISPLAY -->
                        <div id="divisionDisplay" style="display: none;">
                            <div class="division-display">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="percentage-value" id="percentageValue">0%</div>
                                        <div class="division-label">Percentage</div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="division-value" id="divisionValue">N/A</div>
                                        <div class="division-label">Division</div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Grade/Division Selection -->
                            <div class="mt-3">
                                <label for="division_grade" class="form-label">Division/Grade</label>
                                <select class="form-select" id="division_grade" name="division_grade">
                                    <option value="">Select Division/Grade</option>
                                    <option value="1st Division" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == '1st Division') ? 'selected' : ''; ?>>1st Division</option>
                                    <option value="2nd Division" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == '2nd Division') ? 'selected' : ''; ?>>2nd Division</option>
                                    <option value="3rd Division" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == '3rd Division') ? 'selected' : ''; ?>>3rd Division</option>
                                    <option value="Failed" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'Failed') ? 'selected' : ''; ?>>Failed</option>
                                    <option value="A+" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'A+') ? 'selected' : ''; ?>>A+</option>
                                    <option value="A" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'A') ? 'selected' : ''; ?>>A</option>
                                    <option value="B" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'B') ? 'selected' : ''; ?>>B</option>
                                    <option value="C" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'C') ? 'selected' : ''; ?>>C</option>
                                    <option value="D" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'D') ? 'selected' : ''; ?>>D</option>
                                    <option value="Pass" <?php echo (isset($qualification_data['division_grade']) && $qualification_data['division_grade'] == 'Pass') ? 'selected' : ''; ?>>Pass</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 leave blank for auto-calculation</div>
                            </div>
                            
                            <div class="calculation-info">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Division Calculation:</strong><br>
                                • 60% and above: 1st Division<br>
                                • 45% to 59.99%: 2nd Division<br>
                                • 33% to 44.99%: 3rd Division<br>
                                • Below 33%: Failed
                            </div>
                        </div>
                    </div>
                    
                    <!-- ACTION BUTTONS -->
                    <div class="d-flex justify-content-between mt-4">
                        <a href="academic_qualification_view.php" class="btn btn-cancel">
                            <i class="fas fa-times me-2"></i>Cancel
                        </a>
                        <button type="submit" class="btn btn-save">
                            <i class="fas fa-save me-2"></i>
                            <?php echo $is_edit ? 'Update' : 'Save'; ?> 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="emp1_view.php" class="btn btn-primary">
                            <i class="fas fa-user me-2"></i>Go 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>
<!-- Add Flatpickr JS for date picker -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></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 on page load
    function initializeInstitution() {
        const boardSelect = document.getElementById('board_select');
        const uniSelect = document.getElementById('uni_select');
        const customInstitution = document.getElementById('custom_institution');
        const institutionField = document.getElementById('institution');
        
        const currentValue = institutionField.value;
        
        if (!currentValue) return;
        
        if (currentValue.startsWith('Board')) {
            boardSelect.value = currentValue;
        } else if (currentValue.startsWith('Uni')) {
            uniSelect.value = currentValue;
        } else {
            customInstitution.value = currentValue;
        }
    }
    
    // Calculate division
    function calculateDivision() {
        const totalMarks = parseFloat(document.getElementById('total_marks').value) || 0;
        const obtainedMarks = parseFloat(document.getElementById('obtained_marks').value) || 0;
        const divisionDisplay = document.getElementById('divisionDisplay');
        const percentageValue = document.getElementById('percentageValue');
        const divisionValue = document.getElementById('divisionValue');
        const divisionSelect = document.getElementById('division_grade');
        
        if (totalMarks > 0 && obtainedMarks >= 0) {
            const percentage = (obtainedMarks / totalMarks) * 100;
            let division = '';
            let divisionClass = '';
            
            if (percentage >= 60) {
                division = '1st Division';
                divisionClass = 'division-1st';
            } else if (percentage >= 45) {
                division = '2nd Division';
                divisionClass = 'division-2nd';
            } else if (percentage >= 33) {
                division = '3rd Division';
                divisionClass = 'division-3rd';
            } else {
                division = 'Failed';
                divisionClass = 'division-3rd';
            }
            
            percentageValue.textContent = percentage.toFixed(2) + '%';
            divisionValue.textContent = division;
            divisionValue.className = 'division-value ' + divisionClass;
            divisionDisplay.style.display = 'block';
            
            // Auto-select division if not already selected
            if (!divisionSelect.value || divisionSelect.value === '') {
                divisionSelect.value = division;
            }
        } else {
            divisionDisplay.style.display = 'none';
        }
    }
    
    // Auto-fill degree name based on degree type
    document.getElementById('degree_type').addEventListener('change', function() {
        const degreeNameInput = document.getElementById('degree_name');
        const degreeType = this.value;
        
        if (!degreeNameInput.value.trim()) {
            switch(degreeType) {
                case 'Secondary':
                    degreeNameInput.value = 'Secondary School Certificate';
                    break;
                case 'Higher Secondary':
                    degreeNameInput.value = 'Higher Secondary School Certificate';
                    break;
                case 'Bachelor':
                    degreeNameInput.value = 'Bachelor\'s Degree';
                    break;
                case 'Master':
                    degreeNameInput.value = 'Master\'s Degree';
                    break;
                case 'M.Phil':
                    degreeNameInput.value = 'Master of Philosophy';
                    break;
                case 'Ph.D':
                    degreeNameInput.value = 'Doctor of Philosophy';
                    break;
            }
        }
    });
    
    // Initialize Flatpickr calendar
    document.addEventListener('DOMContentLoaded', function() {
        // Get current date for max date limit
        const today = new Date();
        
        // Initialize Flatpickr
        const datePicker = flatpickr("#passing_date", {
            dateFormat: "d/m/Y", // Show as dd/mm/yyyy
            altInput: true,
            altFormat: "d/m/Y", // Also show as dd/mm/yyyy in alt input
            allowInput: true, // Allow manual typing
            clickOpens: true,
            locale: {
                firstDayOfWeek: 1 // Start week on Monday
            },
            maxDate: today, // Don't allow future dates
            monthSelectorType: "static",
            yearRange: [1900, today.getFullYear()],
            onChange: function(selectedDates, dateStr, instance) {
                // Format validation
                if (dateStr && !isValidDate(dateStr)) {
                    instance.clear();
                    alert('Please select a valid date in dd/mm/yyyy format.');
                }
            }
        });
        
        // Also trigger calendar when clicking the icon
        document.getElementById('calendarTrigger').addEventListener('click', function() {
            datePicker.open();
        });
        
        // Initialize other functions
        initializeInstitution();
        calculateDivision();
    });
    
    // Date validation for dd/mm/yyyy format
    function isValidDate(dateString) {
        // Check format dd/mm/yyyy
        const regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
        if (!regex.test(dateString)) {
            return false;
        }
        
        const parts = dateString.split('/');
        const day = parseInt(parts[0], 10);
        const month = parseInt(parts[1], 10);
        const year = parseInt(parts[2], 10);
        
        // Check year range (1900-current year)
        const currentYear = new Date().getFullYear();
        if (year < 1900 || year > currentYear) {
            return false;
        }
        
        // Check month range
        if (month < 1 || month > 12) {
            return false;
        }
        
        // Check day range based on month
        const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        
        // Leap year check for February
        if (month === 2) {
            const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
            if (isLeapYear) {
                if (day < 1 || day > 29) return false;
            } else {
                if (day < 1 || day > 28) return false;
            }
        } else {
            if (day < 1 || day > daysInMonth[month - 1]) return false;
        }
        
        // Check if date is not in the future
        const inputDate = new Date(year, month - 1, day);
        const today = new Date();
        today.setHours(0, 0, 0, 0); // Reset time to compare only dates
        if (inputDate > today) {
            return false;
        }
        
        return true;
    }
    
    // Event listeners
    document.getElementById('total_marks').addEventListener('input', calculateDivision);
    document.getElementById('obtained_marks').addEventListener('input', calculateDivision);
    
    // 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 passing date.');
            document.getElementById('passing_date').focus();
            return false;
        }
        
        if (!isValidDate(passingDate)) {
            e.preventDefault();
            alert('Invalid date. Please use dd/mm/yyyy format and ensure date is valid and not in the future.');
            document.getElementById('passing_date').focus();
            return false;
        }
        
        if (totalMarks <= 0) {
            e.preventDefault();
            alert('Total marks must be greater than zero.');
            document.getElementById('total_marks').focus();
            return false;
        }
        
        if (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;
        }
    });
</script>
</body>
</html>