<?php

// Include session configuration
require_once 'session_config_emp.php';

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

// Check if session is valid
if (!validateUserSession()) {
    // Redirect to login
    header('Location: login_emp.php');
    exit();
}

// Set JSON header
header('Content-Type: application/json');

// Check request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die(json_encode(['success' => false, 'message' => 'Invalid request method']));
}

// Get step from POST data
$step = $_POST['step'] ?? 1;

// Log incoming request for debugging
error_log("========================================");
error_log("SAVE STEP DATA - Step: $step");
error_log("Request method: " . $_SERVER['REQUEST_METHOD']);
error_log("POST data keys: " . implode(', ', array_keys($_POST)));
error_log("FILES data: " . (isset($_FILES['tchpic']) ? 'Photo uploaded' : 'No photo'));
error_log("Session employee_id: " . ($_SESSION['employee_id'] ?? 'NOT SET'));
error_log("Session form_data exists: " . (isset($_SESSION['form_data']) ? 'YES' : 'NO'));

// ✅ FIX: Check if form data exists for steps 2-7
if ($step > 1 && !isset($_SESSION['form_data'])) {
    error_log("❌ ERROR: Step $step attempted without completing step 1 first");
    die(json_encode([
        'success' => false, 
        'message' => 'Please complete step 1 first',
        'redirect' => '?step=1'
    ]));
}

// Check if this is a back navigation save (no need for validation)
$isBackNavigation = isset($_POST['step_2']) || isset($_POST['step_3']) || 
                    isset($_POST['step_4']) || isset($_POST['step_5']) || 
                    isset($_POST['step_6']) || isset($_POST['step_7']);

if ($isBackNavigation) {
    error_log("Back navigation detected for step $step");
    
    // For back navigation, just store the data in session and return success
    $step = $_POST['step'] ?? 1;
    foreach ($_POST as $key => $value) {
        if ($key !== 'csrf_token' && $key !== 'step' && !str_starts_with($key, 'step_')) {
            $_SESSION['form_data'][$key] = $value;
        }
    }
    
    // Preserve photo path if it exists
    if (isset($_SESSION['form_data']['photo_path'])) {
        error_log("Preserved photo path: " . $_SESSION['form_data']['photo_path']);
    }
    
    error_log("Back navigation data saved successfully");
    echo json_encode([
        'success' => true, 
        'message' => 'Progress saved',
        'step' => $step
    ]);
    exit;
}

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

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

error_log("CSRF token validated successfully");

// Database connection
require_once 'connect.php';

// Check database connection
if (!$conn || $conn->connect_error) {
    error_log("❌ Database connection failed: " . ($conn->connect_error ?? 'Unknown error'));
    die(json_encode(['success' => false, 'message' => 'Database connection failed']));
}

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

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

try {
    // Determine which step we're saving
    $step = $_POST['step'] ?? 1;
    $employee_id = $_SESSION['employee_id'] ?? null;

    error_log("=== PROCESSING STEP $step ===");
    error_log("Employee ID from session: " . ($employee_id ?? 'NOT SET'));
    error_log("Session form data keys: " . implode(', ', array_keys($_SESSION['form_data'] ?? [])));
    
    // ✅ CRITICAL FIX: Check if photo path exists in session
    if (isset($_SESSION['form_data']['photo_path'])) {
        error_log("✅ Photo path in session: " . $_SESSION['form_data']['photo_path']);
    } else {
        error_log("⚠️ NO PHOTO PATH IN SESSION!");
    }

    switch($step) {
        case 1:
            // Step 1: Personal Information (employees table)
            saveStep1($conn, $employee_id);
            break;
        case 2:
            // Step 2: Academic Qualifications
            if (!$employee_id) throw new Exception('Employee ID not found. Please complete step 1 first.');
            saveStep2($conn, $employee_id);
            break;
        case 3:
            // Step 3: Professional Qualifications
            if (!$employee_id) throw new Exception('Employee ID not found. Please complete step 1 first.');
            saveStep3($conn, $employee_id);
            break;
        case 4:
            // Step 4: In-Service Training
            if (!$employee_id) throw new Exception('Employee ID not found. Please complete step 1 first.');
            saveStep4($conn, $employee_id);
            break;
        case 5:
            // Step 5: Subjects Teaching
            if (!$employee_id) throw new Exception('Employee ID not found. Please complete step 1 first.');
            saveStep5($conn, $employee_id);
            break;
        case 6:
            // Step 6: Promotion History
            if (!$employee_id) throw new Exception('Employee ID not found. Please complete step 1 first.');
            saveStep6($conn, $employee_id);
            break;
        case 7:
            // Step 7: Transfer History
            if (!$employee_id) throw new Exception('Employee ID not found. Please complete step 1 first.');
            saveStep7($conn, $employee_id);
            break;
        default:
            throw new Exception('Invalid step number');
    }

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

    // Return success response
    error_log("✅ Step $step completed successfully");
    echo json_encode([
        'success' => true,
        'message' => "Step $step data saved successfully",
        'employee_id' => $employee_id,
        'next_step' => $step + 1,
        'current_step' => $step
    ]);

} catch (Exception $e) {
    // Rollback transaction on error
    if (isset($conn) && $conn instanceof mysqli) {
        error_log("Rolling back transaction due to error");
        $conn->rollback();
    }
    
    // Log the error
    error_log("❌ Step save error: " . $e->getMessage());
    error_log("Error trace: " . $e->getTraceAsString());
    
    // Return error response
    echo json_encode([
        'success' => false,
        'message' => 'Error saving data: ' . $e->getMessage(),
        'step' => $step
    ]);
}

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

exit;

// ===== STEP-SPECIFIC SAVE FUNCTIONS =====

function saveStep1($conn, &$employee_id) {
    error_log("=== SAVING STEP 1 ===");
    
    // 1. Check if employee already exists (UPDATE instead of INSERT)
    $personal_no = sanitizeInput($_POST['personalno'] ?? '');
    
    if (empty($personal_no)) {
        throw new Exception('Personal number is required');
    }
    
    error_log("Personal Number: $personal_no");
    
    // Check if employee with this personal number already exists
    $checkSql = "SELECT id FROM employees WHERE personal_no = ?";
    $checkStmt = $conn->prepare($checkSql);
    if (!$checkStmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    $checkStmt->bind_param("s", $personal_no);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    $existingEmployee = $checkResult->fetch_assoc();
    $checkStmt->close();
    
    $isUpdate = !empty($existingEmployee);
    error_log("Employee exists: " . ($isUpdate ? 'YES (UPDATE)' : 'NO (INSERT)'));
    
    // 2. Handle file upload
    $photoPath = 'uploads/employee_photos/default.jpg';
    
    if (isset($_FILES['tchpic']) && $_FILES['tchpic']['error'] === UPLOAD_ERR_OK && !empty($_FILES['tchpic']['name'])) {
        error_log("Processing photo upload...");
        $uploadResult = handleFileUpload('tchpic', $personal_no);
        if ($uploadResult['success']) {
            $photoPath = $uploadResult['file_path'];
            error_log("✅ Photo uploaded successfully: " . $photoPath);
        } else {
            error_log("⚠️ Photo upload failed: " . $uploadResult['message']);
        }
    } else {
        $uploadError = $_FILES['tchpic']['error'] ?? 'No file uploaded';
        error_log("No photo uploaded or upload error: " . $uploadError);
    }
    
    // 3. Store ALL form data in session
    foreach ($_POST as $key => $value) {
        if ($key !== 'csrf_token' && $key !== 'step_1') {
            $_SESSION['form_data'][$key] = $value;
        }
    }
    $_SESSION['form_data']['photo_path'] = $photoPath;
    $_SESSION['form_data']['personalno'] = $personal_no;
    
    error_log("Form data stored in session. Total keys: " . count($_SESSION['form_data'] ?? []));
    
    // 4. Prepare all fields for database
    $full_name = sanitizeInput($_POST['tename']);
    $father_husband_name = sanitizeInput($_POST['tefname']);
    $cnic = sanitizeInput($_POST['tecnic']);
    $gender = sanitizeInput($_POST['tege']);
    $marital_status = isset($_POST['temarst']) ? sanitizeInput($_POST['temarst']) : null;
    $birth_date = convertToMySQLDate($_POST['tebirthday']);
    $retirement_date = convertToMySQLDate($_POST['teretirement']);
    $birth_place = isset($_POST['tebplace']) ? sanitizeInput($_POST['tebplace']) : null;
    $employment_quota_id = (int)($_POST['teemq'] ?? 0);
    $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 = sanitizeInput($_POST['teddono']);
    $next_of_kin_name = sanitizeInput($_POST['tenok']);
    $next_of_kin_relation_id = (int)($_POST['tenokre'] ?? 0);
    $village = isset($_POST['tevillage']) ? sanitizeInput($_POST['tevillage']) : null;
    $post_office = isset($_POST['tepo']) ? sanitizeInput($_POST['tepo']) : null;
    $district_id = (int)($_POST['district'] ?? 0);
    $tehsil_id = (int)($_POST['tehsil'] ?? 0);
    $constituency_id = (int)($_POST['constituency'] ?? 0);
    $union_council_id = (int)($_POST['unionCouncil'] ?? 0);
    $employment_type_id = (int)($_POST['employmentType'] ?? 0);
    $gross_pay = (float)($_POST['grossPay'] ?? 0);
    $initially_appointed_as_id = (int)($_POST['iaa'] ?? 0);
    $appointment_date = convertToMySQLDate($_POST['doapp']);
    $current_designation_id = (int)($_POST['tecudesig'] ?? 0);
    $promotion_date = convertToMySQLDate($_POST['dojcp']);
    $current_bps_id = (int)($_POST['tecups'] ?? 0);
    $current_time_scale_id = (int)($_POST['current_time_scale'] ?? 0);
    $time_scale_date = convertToMySQLDate($_POST['tetimes']);
    $current_school_emis = sanitizeInput($_POST['workin']);
    $working_since = convertToMySQLDate($_POST['wtis']);

    error_log("Saving employee with photo path: " . $photoPath);
    
    // 5. INSERT or UPDATE based on whether employee exists
    if ($isUpdate) {
        // UPDATE existing employee
        $employee_id = $existingEmployee['id'];
        error_log("Updating existing employee with ID: $employee_id");
        
        $sql = "UPDATE employees SET
            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 = ?, 
            employment_type_id = ?, gross_pay = ?, 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 = ?,
            updated_at = NOW()
            WHERE personal_no = ?";
        
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        // Bind parameters
        $stmt->bind_param(
            "sssssssisssssissiiiiiisssiiissss",
            $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, 
            $employment_type_id, $gross_pay, $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,
            $personal_no
        );
    } else {
        // INSERT new employee
        error_log("Inserting new employee");
        
        $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, 
            employment_type_id, gross_pay, 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, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $stmt->bind_param(
            "sssssssssisssssissiiiiiisssiiisss",
            $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, 
            $employment_type_id, $gross_pay, $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 (!$stmt->execute()) {
        $error = $stmt->error;
        error_log("Database execution error: " . $error);
        $stmt->close();
        throw new Exception("Database error: " . $error);
    }
    
    if (!$isUpdate) {
        $employee_id = $conn->insert_id;
        error_log("New employee created with ID: $employee_id");
    } else {
        error_log("Employee updated with ID: $employee_id");
    }
    
    $_SESSION['employee_id'] = $employee_id;
    $stmt->close();
    
    error_log("✅ Employee saved successfully with ID: " . $employee_id);
    error_log("✅ Photo path saved: " . $photoPath);
}

function saveStep2($conn, $employee_id) {
    error_log("=== SAVING STEP 2 (Academic Qualifications) ===");
    
    // ✅ FIX: Only store data in session, don't lose existing data
    $academicFields = [
        'tesscpass', 'tesscsub', 'tesscuni', 'tessctot', 'tesscom', 'tesscdiv',
        'tehscpass', 'tehscsub', 'tehscuni', 'tehsctot', 'tehscom', 'tehscdiv',
        'tebspass', 'tebssub', 'tebsuni', 'tebstot', 'tebsom', 'tebsdiv',
        'temapass', 'temasub', 'temauni', 'tematot', 'temaom', 'temadiv',
        'temphillpass', 'temphillsub', 'temphilluni', 'temphilltot', 'temphillom', 'temphilldiv',
        'tephdpass', 'tephdsub', 'tephduni', 'tephdtot', 'tephdom', 'tephddiv',
        'teotherpass', 'teothersub', 'teotheruni', 'teothertot', 'teotherom', 'teotherdiv'
    ];

    $savedCount = 0;
    foreach ($academicFields as $field) {
        if (isset($_POST[$field])) {
            $_SESSION['form_data'][$field] = $_POST[$field];
            $savedCount++;
        }
    }
    
    error_log("Step 2 completed - $savedCount academic fields stored in session");
    error_log("Photo path still in session: " . ($_SESSION['form_data']['photo_path'] ?? 'MISSING'));
}

function saveStep3($conn, $employee_id) {
    error_log("=== SAVING STEP 3 (Professional Qualifications) ===");
    
    $professionalFields = [
        'teptpass', 'teptis', 'tepttot', 'teptom', 'teptdiv',
        'tebedpass', 'tebedis', 'tebedtot', 'tebedom', 'tebeddiv',
        'temedpass', 'temedis', 'temedtot', 'temedom', 'temeddiv',
        'teo1name', 'teo1pass', 'teo1is', 'teo1tot', 'teo1om', 'teo1div',
        'teo2name', 'teo2pass', 'teo2is', 'teo2tot', 'teo2om', 'teo2div',
        'teo3name', 'teo3pass', 'teo3is', 'teo3tot', 'teo3om', 'teo3div'
    ];

    $savedCount = 0;
    foreach ($professionalFields as $field) {
        if (isset($_POST[$field])) {
            $_SESSION['form_data'][$field] = $_POST[$field];
            $savedCount++;
        }
    }
    
    error_log("Step 3 completed - $savedCount professional fields stored");
    error_log("Photo path still in session: " . ($_SESSION['form_data']['photo_path'] ?? 'MISSING'));
}

function saveStep4($conn, $employee_id) {
    error_log("=== SAVING STEP 4 (In-Service Training) ===");
    
    $savedCount = 0;
    for ($i = 1; $i <= 5; $i++) {
        $trainingFields = ["tr{$i}name", "tr{$i}year", "tr{$i}institute", "tr{$i}place", "tr{$i}duration"];
        foreach ($trainingFields as $field) {
            if (isset($_POST[$field])) {
                $_SESSION['form_data'][$field] = $_POST[$field];
                $savedCount++;
            }
        }
    }
    
    error_log("Step 4 completed - $savedCount training fields stored");
}

function saveStep5($conn, $employee_id) {
    error_log("=== SAVING STEP 5 (Subjects Teaching) ===");
    
    $savedCount = 0;
    for ($i = 1; $i <= 10; $i++) {
        $subjectFields = ["tesubject{$i}", "teclass{$i}", "teperiod{$i}"];
        foreach ($subjectFields as $field) {
            if (isset($_POST[$field])) {
                $_SESSION['form_data'][$field] = $_POST[$field];
                $savedCount++;
            }
        }
    }
    
    error_log("Step 5 completed - $savedCount subject fields stored");
}

function saveStep6($conn, $employee_id) {
    error_log("=== SAVING STEP 6 (Promotion History) ===");
    
    $savedCount = 0;
    for ($i = 1; $i <= 5; $i++) {
        $promotionFields = ["tepredesig{$i}", "teprescale{$i}", "tenewdesig{$i}", "tenewscale{$i}", "teprodate{$i}"];
        foreach ($promotionFields as $field) {
            if (isset($_POST[$field])) {
                $_SESSION['form_data'][$field] = $_POST[$field];
                $savedCount++;
            }
        }
    }
    
    error_log("Step 6 completed - $savedCount promotion fields stored");
}

function saveStep7($conn, $employee_id) {
    error_log("=== SAVING STEP 7 (Transfer History) ===");
    
    $savedCount = 0;
    for ($i = 1; $i <= 5; $i++) {
        $transferFields = ["tetfrom{$i}", "tetto{$i}", "tetreason{$i}", "tetdate{$i}"];
        foreach ($transferFields as $field) {
            if (isset($_POST[$field])) {
                $_SESSION['form_data'][$field] = $_POST[$field];
                $savedCount++;
            }
        }
    }
    
    error_log("Step 7 completed - $savedCount transfer fields stored");
    error_log("FINAL CHECK - Photo path in session: " . ($_SESSION['form_data']['photo_path'] ?? 'MISSING'));
    error_log("Total session data keys: " . count($_SESSION['form_data'] ?? []));
}

// ===== HELPER FUNCTIONS =====

function convertToMySQLDate($date) {
    if (empty($date) || $date === 'dd-mm-yyyy') return null;
    
    $parts = explode('-', $date);
    if (count($parts) === 3) {
        $day = intval($parts[0]);
        $month = intval($parts[1]);
        $year = intval($parts[2]);
        
        // Validate date
        if (checkdate($month, $day, $year)) {
            return sprintf('%04d-%02d-%02d', $year, $month, $day);
        }
    }
    return null;
}

function handleFileUpload($fieldName, $personal_no, $targetDir = "uploads/employee_photos/") {
    try {
        error_log("Starting file upload for personal no: " . $personal_no);
        
        if (!isset($_FILES[$fieldName])) {
            throw new Exception('No file uploaded');
        }

        $file = $_FILES[$fieldName];
        error_log("File details - Name: {$file['name']}, Size: {$file['size']}, Error: {$file['error']}");
        
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $errorMessages = [
                UPLOAD_ERR_INI_SIZE => 'File size exceeds server limit',
                UPLOAD_ERR_FORM_SIZE => 'File size exceeds form limit',
                UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
                UPLOAD_ERR_NO_FILE => 'No file was uploaded',
                UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
                UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
                UPLOAD_ERR_EXTENSION => 'File upload stopped by extension'
            ];
            throw new Exception('File upload error: ' . ($errorMessages[$file['error']] ?? 'Unknown error'));
        }

        // Create directory if needed
        if (!file_exists($targetDir)) {
            if (!mkdir($targetDir, 0755, true)) {
                throw new Exception('Failed to create upload directory');
            }
            error_log("Created directory: $targetDir");
        }

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

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

        // Generate filename using personal number
        $sanitizedPersonalNo = preg_replace('/[^0-9]/', '', $personal_no);
        if (empty($sanitizedPersonalNo)) {
            $sanitizedPersonalNo = 'temp_' . time();
        }
        
        $newFileName = $sanitizedPersonalNo . '.jpg';
        $targetFilePath = $targetDir . $newFileName;

        // Delete old file if exists
        if (file_exists($targetFilePath)) {
            if (!unlink($targetFilePath)) {
                error_log("Warning: Could not delete old file: $targetFilePath");
            }
        }

        // Resize image
        $resizeResult = resizeImageToExactSize($file['tmp_name'], $targetFilePath);
        
        if (!$resizeResult['success']) {
            throw new Exception('Image processing failed: ' . $resizeResult['message']);
        }

        // Verify the file was created
        if (!file_exists($targetFilePath)) {
            throw new Exception('Processed image file was not created');
        }

        // Set proper permissions
        chmod($targetFilePath, 0644);

        error_log("✅ File upload successful: " . $targetFilePath);
        error_log("File size: " . filesize($targetFilePath) . " bytes");
        
        return [
            'success' => true, 
            'file_path' => $targetFilePath,
            'file_name' => $newFileName,
            'file_size' => filesize($targetFilePath)
        ];
        
    } catch (Exception $e) {
        error_log("❌ FILE UPLOAD ERROR: " . $e->getMessage());
        return [
            'success' => false, 
            'message' => $e->getMessage(),
            'file_path' => 'uploads/employee_photos/default.jpg'
        ];
    }
}

function resizeImageToExactSize($sourcePath, $targetPath) {
    try {
        error_log("Resizing image to 450x600 pixels");
        
        $imageInfo = getimagesize($sourcePath);
        if (!$imageInfo) {
            throw new Exception('Could not read image file');
        }
        
        $originalWidth = $imageInfo[0];
        $originalHeight = $imageInfo[1];
        $mimeType = $imageInfo['mime'];

        error_log("Original image: {$originalWidth}x{$originalHeight}, Type: $mimeType");

        // Create image resource
        switch ($mimeType) {
            case 'image/jpeg':
            case 'image/jpg':
                $sourceImage = imagecreatefromjpeg($sourcePath);
                break;
            case 'image/png':
                $sourceImage = imagecreatefrompng($sourcePath);
                // Preserve transparency for PNG
                imagesavealpha($sourceImage, true);
                break;
            default:
                throw new Exception('Unsupported image format: ' . $mimeType);
        }
        
        if (!$sourceImage) {
            throw new Exception('Could not create image resource');
        }

        // Calculate scaling
        $requiredWidthPixels = 450;
        $requiredHeightPixels = 600;
        
        $widthRatio = $requiredWidthPixels / $originalWidth;
        $heightRatio = $requiredHeightPixels / $originalHeight;
        $scale = min($widthRatio, $heightRatio);
        
        $newWidth = round($originalWidth * $scale);
        $newHeight = round($originalHeight * $scale);

        // Create new image
        $newImage = imagecreatetruecolor($requiredWidthPixels, $requiredHeightPixels);
        if (!$newImage) {
            throw new Exception('Could not create new image resource');
        }
        
        // Fill with white background for JPEG, transparent for PNG
        if ($mimeType === 'image/png') {
            imagesavealpha($newImage, true);
            $transparent = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
            imagefill($newImage, 0, 0, $transparent);
        } else {
            $white = imagecolorallocate($newImage, 255, 255, 255);
            imagefill($newImage, 0, 0, $white);
        }
        
        // Calculate position to center
        $x = round(($requiredWidthPixels - $newWidth) / 2);
        $y = round(($requiredHeightPixels - $newHeight) / 2);

        // Resize and copy
        $resizeResult = imagecopyresampled(
            $newImage, $sourceImage,
            $x, $y, 0, 0,
            $newWidth, $newHeight,
            $originalWidth, $originalHeight
        );
        
        if (!$resizeResult) {
            throw new Exception('Image resize operation failed');
        }

        // Save as JPEG
        $saveResult = imagejpeg($newImage, $targetPath, 90);
        
        // Clean up memory
        imagedestroy($sourceImage);
        imagedestroy($newImage);
        
        if (!$saveResult) {
            throw new Exception('Failed to save processed image');
        }

        error_log("✅ Image resized successfully: {$requiredWidthPixels}x{$requiredHeightPixels}");
        
        return [
            'success' => true,
            'original_dimensions' => "{$originalWidth}x{$originalHeight}",
            'final_dimensions' => "{$requiredWidthPixels}x{$requiredHeightPixels}",
            'file_path' => $targetPath
        ];
        
    } catch (Exception $e) {
        error_log("❌ IMAGE RESIZE ERROR: " . $e->getMessage());
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

// Function to validate CSRF token (make sure this exists in session_config_emp.php)
if (!function_exists('validateCsrfToken')) {
    function validateCsrfToken($token) {
        if (!isset($_SESSION['csrf_token'])) {
            return false;
        }
        return hash_equals($_SESSION['csrf_token'], $token);
    }
}
?>