<?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';

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['qualification_id'])) {
    $qualification_id = intval($_POST['qualification_id']);
    
    // Get employee data from session
    $employee_id = $_SESSION['employee_id'];
    $cnic = $_SESSION['cnic'];
    
    // First, get the personal_no from registrations_emp
    $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'];
            
            // Delete qualification
            $delete_sql = "DELETE FROM academic_qualifications WHERE qualification_id = ? AND employee_id = ?";
            $stmt_delete = $conn->prepare($delete_sql);
            $stmt_delete->bind_param("ii", $qualification_id, $db_employee_id);
            
            if ($stmt_delete->execute()) {
                $_SESSION['academic_success'] = "Qualification deleted successfully!";
            } else {
                $_SESSION['academic_error'] = "Failed to delete qualification: " . $stmt_delete->error;
            }
        } else {
            $_SESSION['academic_error'] = "Employee profile not found.";
        }
    } else {
        $_SESSION['academic_error'] = "Registration record not found.";
    }
    
    header('Location: academic_qualification_view.php');
    exit();
} else {
    $_SESSION['academic_error'] = "Invalid request.";
    header('Location: academic_qualification_view.php');
    exit();
}
?>