<?php
session_start();

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Verify CSRF token
if (!isset($_POST['csrf_token'])) {
    die(json_encode(['success' => false, 'message' => 'CSRF token missing']));
}

if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    die(json_encode(['success' => false, 'message' => 'CSRF token validation failed']));
}

// Database connection
require_once 'connect.php';

// Function to sanitize input data
function sanitizeInput($data) {
    global $conn;
    return $conn->real_escape_string(trim($data));
}

// Enhanced file upload function with CNIC-based naming
function handleFileUpload($fieldName, $cnic, $targetDir = "uploads/teacher_photos/") {
    try {
        // Validate CNIC
        if (empty($cnic)) {
            throw new Exception('CNIC is required for file naming');
        }
        
        // Sanitize CNIC for filename (remove non-numeric characters)
        $sanitizedCnic = preg_replace('/[^0-9]/', '', $cnic);
        if (strlen($sanitizedCnic) != 13) {
            throw new Exception('Invalid CNIC format - must be 13 digits');
        }

        // Standard file upload checks
        if (!isset($_FILES[$fieldName]) || $_FILES[$fieldName]['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('File upload error: ' . $_FILES[$fieldName]['error']);
        }

        // Create directory if needed with proper permissions
        if (!file_exists($targetDir)) {
            if (!mkdir($targetDir, 0755, true)) {
                throw new Exception('Failed to create upload directory');
            }
        }

        $file = $_FILES[$fieldName];
        $fileType = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        // Validate image
        $check = getimagesize($file['tmp_name']);
        if ($check === false) {
            throw new Exception('File is not an image');
        }

        // Check file size (2MB max)
        if ($file['size'] > 2097152) {
            throw new Exception('File size exceeds 2MB limit');
        }

        // Allow certain file formats
        $allowedTypes = ['jpg', 'jpeg', 'png'];
        if (!in_array($fileType, $allowedTypes)) {
            throw new Exception('Only JPG, JPEG, PNG files are allowed');
        }

        // Generate filename using CNIC
        $newFileName = $sanitizedCnic . '.' . $fileType;
        $targetFilePath = $targetDir . $newFileName;

        // Delete old file if exists
        if (file_exists($targetFilePath)) {
            if (!unlink($targetFilePath)) {
                throw new Exception('Failed to remove existing file');
            }
        }

        // Upload file
        if (!move_uploaded_file($file['tmp_name'], $targetFilePath)) {
            throw new Exception('Error moving uploaded file');
        }

        return ['success' => true, 'file_path' => $targetFilePath];
    } catch (Exception $e) {
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

// Start transaction
$conn->begin_transaction();

try {
    // 1. Handle file upload if exists
    $photoPath = null;
    if (!empty($_FILES['tchpic']['name'])) {
        $cnic = sanitizeInput($_POST['tecnic'] ?? '');
        $uploadResult = handleFileUpload('tchpic', $cnic);
        if (!$uploadResult['success']) {
            throw new Exception('Photo upload failed: ' . $uploadResult['message']);
        }
        $photoPath = $uploadResult['file_path'];
    }

    // 2. Prepare basic teacher information
    $requiredFields = [
        'personalno', 'tename', 'tefname', 'tecnic', 'tege', 'tebirthday', 
        'teretirement', 'teemq', 'temobno', 'teddono', 'tenok', 'tenokre', 'district', 'tehsil', 'constituency', 
        'unionCouncil', 'employmentType', 'grossPay', 'iaa', 'doapp', 'tecudesig', 'dojcp', 'tecups', 
        'current_time_scale', 'tetimes', 'workin', 'workin1', 'wtis'
    ];

    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            throw new Exception("Required field '$field' is missing");
        }
    }

    // Validate gender is selected
    if (!isset($_POST['tege'])) {
        throw new Exception('Gender is required');
    }

    // Validate CNIC format
    $cnic = sanitizeInput($_POST['tecnic']);
    if (!preg_match('/^[0-9]{5}-[0-9]{7}-[0-9]{1}$/', $cnic)) {
        throw new Exception('Invalid CNIC format. Please use XXXXX-XXXXXXX-X format');
    }

// Prepare all fields
$personal_no = sanitizeInput($_POST['personalno']);
$full_name = sanitizeInput($_POST['tename']);
$father_husband_name = sanitizeInput($_POST['tefname']);
$cnic = sanitizeInput($_POST['cnic']); 
$gender = sanitizeInput($_POST['tege']);
$marital_status = isset($_POST['temarst']) ? sanitizeInput($_POST['temarst']) : null;
$birth_date = sanitizeInput($_POST['tebirthday']);
$retirement_date = sanitizeInput($_POST['teretirement']);
$birth_place = isset($_POST['tebplace']) ? sanitizeInput($_POST['tebplace']) : null;
$employment_quota_id = (int)$_POST['teemq'];
$mobile_no = sanitizeInput($_POST['temobno']);
$whatsapp_no = isset($_POST['tewano']) ? sanitizeInput($_POST['tewano']) : null;
$gpf_no = isset($_POST['tegpfno']) ? sanitizeInput($_POST['tegpfno']) : null;
$ddo_code = isset($_POST['teddono']) ? sanitizeInput($_POST['teddono']) : null;
$next_of_kin_name = isset($_POST['tenok']) ? sanitizeInput($_POST['tenok']) : null;
$next_of_kin_relation_id = isset($_POST['tenokre']) ? (int)$_POST['tenokre'] : null;
$village = isset($_POST['tevillage']) ? sanitizeInput($_POST['tevillage']) : null;
$post_office = isset($_POST['tepo']) ? sanitizeInput($_POST['tepo']) : null;
$district_id = (int)$_POST['district'];
$tehsil_id = (int)$_POST['tehsil'];
$constituency_id = (int)$_POST['constituency'];
$union_council_id = (int)$_POST['unionCouncil'];
$employmentType_id = (int)$_POST['employmentType'];
$grossPay = sanitizeInput($_POST['grossPay']);
$initially_appointed_as_id = (int)$_POST['iaa'];
$appointment_date = sanitizeInput($_POST['doapp']);
$current_designation_id = (int)$_POST['tecudesig'];
$promotion_date = sanitizeInput($_POST['dojcp']);
$current_bps_id = (int)$_POST['tecups'];
$current_time_scale_id = (int)$_POST['current_time_scale'];
$time_scale_date = sanitizeInput($_POST['tetimes']);
$current_school_emis = (int)$_POST['workin'];
$working_since = sanitizeInput($_POST['wtis']);
$current_school_name = isset($_POST['workin1']) ? sanitizeInput($_POST['workin1']) : null;
$photoPath = isset($_FILES['photo']['name']) ? sanitizeInput($_FILES['photo']['name']) : null;

// Insert into employees table
$sql = "INSERT INTO employees (
    personal_no, full_name, father_husband_name, cnic, gender, marital_status, 
    birth_date, retirement_date, birth_place, employment_quota_id, mobile_no, 
    whatsapp_no, gpf_no, ddo_code, next_of_kin_name, next_of_kin_relation_id, 
    village, post_office, district_id, tehsil_id, constituency_id, union_council_id, employmentType_id, grossPay,
    initially_appointed_as_id, appointment_date, current_designation_id, promotion_date,
    current_bps_id, current_time_scale_id, time_scale_date, current_school_emis, 
    working_since, photo_path
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    throw new Exception("Prepare failed: " . $conn->error);
}

// Corrected type string
$bindResult = $stmt->bind_param(
    "sssssssssisssssissiiiiiisssiiisiss",
    $personal_no, $full_name, $father_husband_name, $cnic, $gender, $marital_status,
    $birth_date, $retirement_date, $birth_place, $employment_quota_id, $mobile_no,
    $whatsapp_no, $gpf_no, $ddo_code, $next_of_kin_name, $next_of_kin_relation_id,
    $village, $post_office, $district_id, $tehsil_id, $constituency_id, $union_council_id, $employmentType_id, $grossPay,
    $initially_appointed_as_id, $appointment_date, $current_designation_id, $promotion_date,
    $current_bps_id, $current_time_scale_id, $time_scale_date, $current_school_emis,
    $working_since, $photoPath
);

if (!$bindResult) {
    throw new Exception("Bind failed: " . $stmt->error);
}

    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    $employee_id = $conn->insert_id;
    $stmt->close();

    // 3. Insert academic qualifications
    $academicDegrees = [
        'tesscpass' => ['type' => 'Secondary', 'name' => 'Secondary Certificate'],
        'tehscpass' => ['type' => 'Higher Secondary', 'name' => 'Higher Secondary Certificate'],
        'tebspass' => ['type' => 'Bachelor', 'name' => 'B.A/B.Sc/BS'],
        'temapass' => ['type' => 'Master', 'name' => 'M.A/M.Sc/MCS'],
        'temapass2' => ['type' => 'Master', 'name' => 'Master In Other Subject'],
        'temapass3' => ['type' => 'Master', 'name' => 'Master In Other Subject'],
        'temphillpass' => ['type' => 'M.Phil', 'name' => 'M.Phil'],
        'tephdpass' => ['type' => 'Ph.D', 'name' => 'Ph.D'],
        'teotherpass' => ['type' => 'Other', 'name' => 'Other']
    ];

    foreach ($academicDegrees as $passField => $degreeInfo) {
        if (!empty($_POST[$passField])) {
            $passing_year = sanitizeInput($_POST[$passField]);
            $subjects = isset($_POST[str_replace('pass', 'sub', $passField)]) ? sanitizeInput($_POST[str_replace('pass', 'sub', $passField)]) : '';
            $university_board = isset($_POST[str_replace('pass', 'uni', $passField)]) ? sanitizeInput($_POST[str_replace('pass', 'uni', $passField)]) : '';
            $total_marks = isset($_POST[str_replace('pass', 'tot', $passField)]) ? (float)$_POST[str_replace('pass', 'tot', $passField)] : 0;
            $obtained_marks = isset($_POST[str_replace('pass', 'om', $passField)]) ? (float)$_POST[str_replace('pass', 'om', $passField)] : 0;
            $division_grade = isset($_POST[str_replace('pass', 'div', $passField)]) ? sanitizeInput($_POST[str_replace('pass', 'div', $passField)]) : '';

            $sql = "INSERT INTO academic_qualifications (
                employee_id, degree_type, degree_name, passing_year, subjects, 
                university_board, total_marks, obtained_marks, division_grade
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed for academic: " . $conn->error);
            }

            $bindResult = $stmt->bind_param(
                "isssssdds",
                $employee_id, $degreeInfo['type'], $degreeInfo['name'], $passing_year, 
                $subjects, $university_board, $total_marks, $obtained_marks, $division_grade
            );

            if (!$bindResult) {
                throw new Exception("Bind failed for academic: " . $stmt->error);
            }

            if (!$stmt->execute()) {
                throw new Exception("Execute failed for academic: " . $stmt->error);
            }
            $stmt->close();
        }
    }

    // 4. Insert professional qualifications
    $professionalDegrees = [
        'teptpass' => 'PT/CT',
        'tebedpass' => 'B.Ed/BS.Ed',
        'temedpass' => 'M.Ed/M.A Education'
    ];

    foreach ($professionalDegrees as $passField => $qualification_name) {
        if (!empty($_POST[$passField])) {
            $passing_year = sanitizeInput($_POST[$passField]);
            $institution = sanitizeInput($_POST[str_replace('pass', 'is', $passField)]);
            $total_marks = (float)$_POST[str_replace('pass', 'tot', $passField)];
            $obtained_marks = (float)$_POST[str_replace('pass', 'om', $passField)];
            $division_grade = sanitizeInput($_POST[str_replace('pass', 'div', $passField)]);

            $sql = "INSERT INTO professional_qualifications (
                employee_id, qualification_name, passing_year, institution, 
                total_marks, obtained_marks, division_grade
            ) VALUES (?, ?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed for professional: " . $conn->error);
            }

            $bindResult = $stmt->bind_param(
                "isssdds",
                $employee_id, $qualification_name, $passing_year, $institution,
                $total_marks, $obtained_marks, $division_grade
            );

            if (!$bindResult) {
                throw new Exception("Bind failed for professional: " . $stmt->error);
            }

            if (!$stmt->execute()) {
                throw new Exception("Execute failed for professional: " . $stmt->error);
            }
            $stmt->close();
        }
    }

    // 5. Insert other professional qualifications (up to 3)
    for ($i = 1; $i <= 3; $i++) {
        $qualification_name = $_POST["teo{$i}name"] ?? '';
        if (!empty($qualification_name)) {
            $qualification_name = sanitizeInput($qualification_name);
            $passing_year = sanitizeInput($_POST["teo{$i}pass"]);
            $institution = sanitizeInput($_POST["teo{$i}is"]);
            $total_marks = (float)$_POST["teo{$i}tot"];
            $obtained_marks = (float)$_POST["teo{$i}om"];
            $division_grade = sanitizeInput($_POST["teo{$i}div"]);

            $sql = "INSERT INTO professional_qualifications (
                employee_id, qualification_name, passing_year, institution, 
                total_marks, obtained_marks, division_grade
            ) VALUES (?, ?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed for other professional: " . $conn->error);
            }

            $bindResult = $stmt->bind_param(
                "isssdds",
                $employee_id, $qualification_name, $passing_year, $institution,
                $total_marks, $obtained_marks, $division_grade
            );

            if (!$bindResult) {
                throw new Exception("Bind failed for other professional: " . $stmt->error);
            }

            if (!$stmt->execute()) {
                throw new Exception("Execute failed for other professional: " . $stmt->error);
            }
            $stmt->close();
        }
    }

    // 6. Insert in-service training (up to 5)
    for ($i = 1; $i <= 5; $i++) {
        $training_name = $_POST["tr{$i}name"] ?? '';
        if (!empty($training_name)) {
            $training_name = sanitizeInput($training_name);
            $training_year = sanitizeInput($_POST["tr{$i}year"]);
            $institution = sanitizeInput($_POST["tr{$i}institute"]);
            $place = sanitizeInput($_POST["tr{$i}place"]);
            $duration_days = (int)$_POST["tr{$i}duration"];

            $sql = "INSERT INTO trainings (
                employee_id, training_name, training_year, institution, 
                place, duration_days
            ) VALUES (?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed for training: " . $conn->error);
            }

            $bindResult = $stmt->bind_param(
                "issssi",
                $employee_id, $training_name, $training_year, $institution, 
                $place, $duration_days
            );

            if (!$bindResult) {
                throw new Exception("Bind failed for training: " . $stmt->error);
            }

            if (!$stmt->execute()) {
                throw new Exception("Execute failed for training: " . $stmt->error);
            }
            $stmt->close();
        }
    }

    // 7. Insert subjects teaching (up to 10)
    for ($i = 1; $i <= 10; $i++) {
        $subject_code = $_POST["tesubject{$i}"] ?? 0;
        $class_id = $_POST["teclass{$i}"] ?? 0;
        $periods_per_week = (int)$_POST["teperiod{$i}"];

        if ($subject_code > 0 && $class_id > 0 && $periods_per_week > 0) {
            $sql = "INSERT INTO subjects_taught (
                employee_id, subject_code, class_id, periods_per_week
            ) VALUES (?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed for subject: " . $conn->error);
            }

            $bindResult = $stmt->bind_param(
                "iiii",
                $employee_id, $subject_code, $class_id, $periods_per_week
            );

            if (!$bindResult) {
                throw new Exception("Bind failed for subject: " . $stmt->error);
            }

            if (!$stmt->execute()) {
                throw new Exception("Execute failed for subject: " . $stmt->error);
            }
            $stmt->close();
        }
    }

    // 8. Insert promotion history (up to 5)
    for ($i = 1; $i <= 5; $i++) {
        $previous_designation_id = $_POST["tepredesig{$i}"] ?? 0;
        $previous_scale_id = $_POST["teprescale{$i}"] ?? 0;
        $new_designation_id = $_POST["tenewdesig{$i}"] ?? 0;
        $new_scale_id = $_POST["tenewscale{$i}"] ?? 0;
        $promotion_date = $_POST["teprodate{$i}"] ?? '';

        if ($previous_designation_id > 0 && $previous_scale_id > 0 && 
            $new_designation_id > 0 && $new_scale_id > 0 && !empty($promotion_date)) {
            $sql = "INSERT INTO promotions (
                employee_id, previous_designation_id, previous_scale_id, 
                new_designation_id, new_scale_id, promotion_date
            ) VALUES (?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed for promotion: " . $conn->error);
            }

            $bindResult = $stmt->bind_param(
                "iiiiis",
                $employee_id, $previous_designation_id, $previous_scale_id,
                $new_designation_id, $new_scale_id, $promotion_date
            );

            if (!$bindResult) {
                throw new Exception("Bind failed for promotion: " . $stmt->error);
            }

            if (!$stmt->execute()) {
                throw new Exception("Execute failed for promotion: " . $stmt->error);
            }
            $stmt->close();
        }
    }

    // 9. Insert transfer history (up to 5)
    for ($i = 1; $i <= 5; $i++) {
        $from_school_emis = $_POST["tetfrom{$i}"] ?? '';
        $to_school_emis = $_POST["tetto{$i}"] ?? '';
        $reason_id = $_POST["tetreason{$i}"] ?? 0;
        $transfer_date = $_POST["tetdate{$i}"] ?? '';

        if (!empty($from_school_emis) && !empty($to_school_emis) && 
            $reason_id > 0 && !empty($transfer_date)) {
            $sql = "INSERT INTO transfers (
                employee_id, from_school_emis, to_school_emis, 
                reason_id, transfer_date
            ) VALUES (?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed for transfer: " . $conn->error);
            }

            $bindResult = $stmt->bind_param(
                "ssiis",
                $employee_id, $from_school_emis, $to_school_emis,
                $reason_id, $transfer_date
            );

            if (!$bindResult) {
                throw new Exception("Bind failed for transfer: " . $stmt->error);
            }

            if (!$stmt->execute()) {
                throw new Exception("Execute failed for transfer: " . $stmt->error);
            }
            $stmt->close();
        }
    }

    // Commit transaction
    $conn->commit();


    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Employee profile saved successfully',
        'employee_id' => $employee_id,
        'photo_path' => $photoPath
    ]);

} catch (Exception $e) {
    // Rollback transaction on error
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->rollback();
    }
    
    // Log the error
    error_log("Employee save error: " . $e->getMessage());
    
    // Return error response
    echo json_encode([
        'success' => false,
        'message' => 'Error saving employee profile: ' . $e->getMessage()
    ]);
}

if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>