<?php
session_start();

// Validate CSRF token
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die('CSRF token validation failed');
}

// Include database connection
include_once 'connect.php';

// Collect all form data from session
$step1_data = $_SESSION['step1_data'] ?? [];
$step2_data = $_SESSION['step2_data'] ?? [];
$step3_data = $_SESSION['step3_data'] ?? [];
$step4_data = $_SESSION['step4_data'] ?? [];
$step5_data = $_SESSION['step5_data'] ?? [];
$step6_data = $_SESSION['step6_data'] ?? [];
$step7_data = $_POST; // Current step data

try {
    // Begin transaction
    $conn->begin_transaction();
    
    // Insert basic employee information
    $sql = "INSERT INTO employees (
        personal_no, full_name, father_name, cnic, gender, marital_status, 
        dob, retirement_date, birth_place, employment_quota, mobile_no, 
        whatsapp_no, gpf_no, ddo_code, next_of_kin, next_of_kin_relation,
        village, post_office, district_id, tehsil_id, constituency_id, 
        union_council_id, employment_type, gross_pay, initial_designation, 
        appointment_date, current_designation, promotion_date, bps_scale, 
        time_scale, time_scale_date, emis_code, working_since, photo
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    
    // Handle file upload
    $photo_path = '';
    if (isset($_FILES['tchpic']) && $_FILES['tchpic']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = 'uploads/employee_photos/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_extension = pathinfo($_FILES['tchpic']['name'], PATHINFO_EXTENSION);
        $photo_filename = $step1_data['personalno'] . '_' . time() . '.' . $file_extension;
        $photo_path = $upload_dir . $photo_filename;
        
        move_uploaded_file($_FILES['tchpic']['tmp_name'], $photo_path);
    }
    
    $stmt->bind_param(
        "ssssssssssssssssssiiiiissssssssssssss",
        $step1_data['personalno'],
        $step1_data['tename'],
        $step1_data['tefname'],
        $step1_data['tecnic'],
        $step1_data['tege'],
        $step1_data['temarst'],
        $step1_data['tebirthday'],
        $step1_data['teretirement'],
        $step1_data['tebplace'],
        $step1_data['teemq'],
        $step1_data['temobno'],
        $step1_data['tewano'],
        $step1_data['tegpfno'],
        $step1_data['teddono'],
        $step1_data['tenok'],
        $step1_data['tenokre'],
        $step1_data['tevillage'],
        $step1_data['tepo'],
        $step1_data['district'],
        $step1_data['tehsil'],
        $step1_data['constituency'],
        $step1_data['unionCouncil'],
        $step1_data['employmentType'],
        $step1_data['grossPay'],
        $step1_data['iaa'],
        $step1_data['doapp'],
        $step1_data['tecudesig'],
        $step1_data['dojcp'],
        $step1_data['tecups'],
        $step1_data['current_time_scale'],
        $step1_data['tetimes'],
        $step1_data['workin'],
        $step1_data['wtis'],
        $photo_path
    );
    
    $stmt->execute();
    $employee_id = $conn->insert_id;
    $stmt->close();
    
    // Insert academic qualifications
    $academic_degrees = [
        'tessc' => 'Secondary Certificate',
        'tehsc' => 'Higher Secondary Certificate',
        'tebs' => 'B.A/B.Sc/BS',
        'tema' => 'M.A/M.Sc/MCS',
        'temapass2' => 'Master In Other Subject',
        'temapass3' => 'Master In Other Subject',
        'temphill' => 'M.Phil',
        'tephd' => 'Ph.D',
        'teother' => 'Other'
    ];
    
    foreach ($academic_degrees as $prefix => $degree_name) {
        if (!empty($step2_data[$prefix . 'pass'])) {
            $sql = "INSERT INTO employee_education (
                employee_id, degree_name, pass_date, subjects, university, 
                total_marks, obtained_marks, grade_division
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param(
                "issssiis",
                $employee_id,
                $degree_name,
                $step2_data[$prefix . 'pass'],
                $step2_data[$prefix . 'sub'],
                $step2_data[$prefix . 'uni'],
                $step2_data[$prefix . 'tot'],
                $step2_data[$prefix . 'om'],
                $step2_data[$prefix . 'div']
            );
            $stmt->execute();
            $stmt->close();
        }
    }
    
    // Insert professional qualifications
    $professional_degrees = [
        'tept' => 'PT/CT',
        'tebed' => 'B.Ed/BS.Ed',
        'temed' => 'M.Ed/M.A Education',
        'teo1' => $step3_data['teo1name'] ?? 'Other Qualification 1',
        'teo2' => $step3_data['teo2name'] ?? 'Other Qualification 2',
        'teo3' => $step3_data['teo3name'] ?? 'Other Qualification 3'
    ];
    
    foreach ($professional_degrees as $prefix => $degree_name) {
        if (!empty($step3_data[$prefix . 'pass']) || !empty($step3_data[$prefix . 'name'])) {
            $sql = "INSERT INTO employee_professional_qualifications (
                employee_id, qualification_name, pass_date, institution, 
                total_marks, obtained_marks, grade_division
            ) VALUES (?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param(
                "isssiis",
                $employee_id,
                $degree_name,
                $step3_data[$prefix . 'pass'] ?? null,
                $step3_data[$prefix . 'is'] ?? null,
                $step3_data[$prefix . 'tot'] ?? null,
                $step3_data[$prefix . 'om'] ?? null,
                $step3_data[$prefix . 'div'] ?? null
            );
            $stmt->execute();
            $stmt->close();
        }
    }
    
    // Insert training records
    for ($i = 1; $i <= 5; $i++) {
        if (!empty($step4_data["tr{$i}name"])) {
            $sql = "INSERT INTO employee_trainings (
                employee_id, training_title, training_year, institute, 
                place, duration_days
            ) VALUES (?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param(
                "issssi",
                $employee_id,
                $step4_data["tr{$i}name"],
                $step4_data["tr{$i}year"],
                $step4_data["tr{$i}institute"],
                $step4_data["tr{$i}place"],
                $step4_data["tr{$i}duration"]
            );
            $stmt->execute();
            $stmt->close();
        }
    }
    
    // Insert subjects taught
    for ($i = 1; $i <= 10; $i++) {
        if (!empty($step5_data["tesubject{$i}"]) && !empty($step5_data["teclass{$i}"])) {
            $sql = "INSERT INTO employee_subjects (
                employee_id, subject_id, class_id, periods_per_week
            ) VALUES (?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param(
                "iiii",
                $employee_id,
                $step5_data["tesubject{$i}"],
                $step5_data["teclass{$i}"],
                $step5_data["teperiod{$i}"]
            );
            $stmt->execute();
            $stmt->close();
        }
    }
    
    // Insert promotion history
    for ($i = 1; $i <= 5; $i++) {
        if (!empty($step6_data["tepredesig{$i}"]) && !empty($step6_data["tenewdesig{$i}"])) {
            $sql = "INSERT INTO employee_promotions (
                employee_id, previous_designation_id, previous_scale_id, 
                new_designation_id, new_scale_id, promotion_date
            ) VALUES (?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param(
                "iiiiis",
                $employee_id,
                $step6_data["tepredesig{$i}"],
                $step6_data["teprescale{$i}"],
                $step6_data["tenewdesig{$i}"],
                $step6_data["tenewscale{$i}"],
                $step6_data["teprodate{$i}"]
            );
            $stmt->execute();
            $stmt->close();
        }
    }
    
    // Insert transfer history
    for ($i = 1; $i <= 5; $i++) {
        if (!empty($step7_data["tetfrom{$i}"]) && !empty($step7_data["tetto{$i}"])) {
            $sql = "INSERT INTO employee_transfers (
                employee_id, from_school_emis, to_school_emis, 
                reason_id, transfer_date
            ) VALUES (?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param(
                "sssis",
                $employee_id,
                $step7_data["tetfrom{$i}"],
                $step7_data["tetto{$i}"],
                $step7_data["tetreason{$i}"],
                $step7_data["tetdate{$i}"]
            );
            $stmt->execute();
            $stmt->close();
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    // Clear session data
    session_unset();
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Employee profile saved successfully',
        'employee_id' => $employee_id
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Return error response
    echo json_encode([
        'success' => false,
        'message' => 'Error saving employee profile: ' . $e->getMessage()
    ]);
}