<?php
/**
* School Step 10: Photo Upload and Collage Generation - SAVE PROCESSING
*
* @author School Management System
* @version 2.7
* @copyright 2026
*/
require_once 'session_config_school.php';
if (!validateSchoolSession()) {
    header("Location: login.php");
    exit;
}
require_once 'school_profile_completion_check.php';
include_once 'connect.php';
require_once 'photo_config.php';

// ============================================================================
// ERROR REPORTING
// ============================================================================
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/school_step10_save_errors.log');
ini_set('memory_limit', '256M');
ini_set('max_execution_time', 300);

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
function get_session_value($key, $default = '') {
    return isset($_SESSION[$key]) ? $_SESSION[$key] : $default;
}

function logError($message, $context = []) {
    $log_dir = __DIR__ . '/logs/';
    if (!file_exists($log_dir)) mkdir($log_dir, 0755, true);
    $log_file = $log_dir . 'photo_upload_' . date('Y-m-d') . '.log';
    $timestamp = date('Y-m-d H:i:s');
    $context_str = !empty($context) ? ' | Context: ' . json_encode($context) : '';
    file_put_contents($log_file, "[$timestamp] $message$context_str" . PHP_EOL, FILE_APPEND);
}

function validateImageFile($filepath) {
    if (!file_exists($filepath)) return false;
    $image_info = @getimagesize($filepath);
    if (!$image_info) return false;
    $allowed_mime = unserialize(ALLOWED_MIME_TYPES);
    return in_array($image_info['mime'], $allowed_mime);
}

function stripExifData($image_path) {
    $image = @imagecreatefromstring(file_get_contents($image_path));
    if (!$image) return $image_path;
    $stripped_path = $image_path . '_stripped.jpg';
    imagejpeg($image, $stripped_path, 90);
    imagedestroy($image);
    @unlink($image_path);
    @rename($stripped_path, $image_path);
    return $image_path;
}

function optimizeImage($source_path, $quality = 85) {
    $info = getimagesize($source_path);
    if (!$info) return false;
    if (filesize($source_path) < 1024 * 1024) return true;
    $temp_path = $source_path . '_optimized';
    switch ($info[2]) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($source_path);
            imagejpeg($image, $temp_path, $quality);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($source_path);
            imagepng($image, $temp_path, 9);
            break;
        default: return true;
    }
    imagedestroy($image);
    if (file_exists($temp_path) && filesize($temp_path) < filesize($source_path)) {
        unlink($source_path);
        rename($temp_path, $source_path);
    } elseif (file_exists($temp_path)) {
        unlink($temp_path);
    }
    return true;
}

function createThumbnail($source_path, $max_dimension) {
    $image_info = @getimagesize($source_path);
    if (!$image_info) return $source_path;
    $width = $image_info[0];
    $height = $image_info[1];
    if ($width <= $max_dimension && $height <= $max_dimension) return $source_path;
    $ratio = $width / $height;
    if ($ratio > 1) {
        $new_width = $max_dimension;
        $new_height = $max_dimension / $ratio;
    } else {
        $new_height = $max_dimension;
        $new_width = $max_dimension * $ratio;
    }
    $thumb = imagecreatetruecolor((int)$new_width, (int)$new_height);
    $source = loadImage($source_path, $image_info[2]);
    if (!$source) return $source_path;
    imagecopyresampled($thumb, $source, 0, 0, 0, 0, (int)$new_width, (int)$new_height, $width, $height);
    $thumb_path = $source_path . '_thumb.jpg';
    imagejpeg($thumb, $thumb_path, 85);
    imagedestroy($source);
    imagedestroy($thumb);
    return $thumb_path;
}

function loadImage($path, $type) {
    switch ($type) {
        case IMAGETYPE_JPEG: return @imagecreatefromjpeg($path);
        case IMAGETYPE_PNG:
            $img = @imagecreatefrompng($path);
            if ($img) { imagealphablending($img, false); imagesavealpha($img, true); }
            return $img;
        case IMAGETYPE_GIF: return @imagecreatefromgif($path);
        case IMAGETYPE_WEBP: return @imagecreatefromwebp($path);
        default: return false;
    }
}

function deleteOldPhotosAndCollage($conn, $emis_code, $upload_dir) {
    try {
        $stmt = $conn->prepare("SELECT id, file_path FROM school_photos WHERE emis_code = ?");
        if (!$stmt) return false;
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $file_path = $upload_dir . $row['file_path'];
            if (file_exists($file_path)) @unlink($file_path);
        }
        $stmt->close();
        
        $collage_stmt = $conn->prepare("SELECT collage_filename FROM school_collages WHERE emis_code = ?");
        if ($collage_stmt) {
            $collage_stmt->bind_param("s", $emis_code);
            $collage_stmt->execute();
            $collage_result = $collage_stmt->get_result();
            while ($collage_row = $collage_result->fetch_assoc()) {
                $collage_path = $upload_dir . $collage_row['collage_filename'];
                if (file_exists($collage_path)) @unlink($collage_path);
            }
            $collage_stmt->close();
        }
        
        $delete_stmt = $conn->prepare("DELETE FROM school_photos WHERE emis_code = ?");
        if ($delete_stmt) {
            $delete_stmt->bind_param("s", $emis_code);
            $delete_stmt->execute();
            $delete_stmt->close();
        }
        return true;
    } catch (Exception $e) {
        logError("Error deleting old assets: " . $e->getMessage(), ['emis_code' => $emis_code]);
        return false;
    }
}

function calculateOptimalLayout($count) {
    $layouts = [
        3 => [
            ['x' => 0.05, 'y' => 0.15, 'width' => 0.60, 'height' => 0.70],
            ['x' => 0.68, 'y' => 0.15, 'width' => 0.27, 'height' => 0.33],
            ['x' => 0.68, 'y' => 0.52, 'width' => 0.27, 'height' => 0.33],
        ],
        4 => [
            ['x' => 0.05, 'y' => 0.15, 'width' => 0.42, 'height' => 0.70],
            ['x' => 0.49, 'y' => 0.15, 'width' => 0.48, 'height' => 0.33],
            ['x' => 0.49, 'y' => 0.52, 'width' => 0.48, 'height' => 0.33],
            ['x' => 0.05, 'y' => 0.52, 'width' => 0.42, 'height' => 0.33],
        ],
        5 => [
            ['x' => 0.03, 'y' => 0.15, 'width' => 0.30, 'height' => 0.70],
            ['x' => 0.35, 'y' => 0.15, 'width' => 0.30, 'height' => 0.33],
            ['x' => 0.35, 'y' => 0.52, 'width' => 0.30, 'height' => 0.33],
            ['x' => 0.67, 'y' => 0.15, 'width' => 0.30, 'height' => 0.33],
            ['x' => 0.67, 'y' => 0.52, 'width' => 0.30, 'height' => 0.33],
        ]
    ];
    return $layouts[$count] ?? $layouts[3];
}

function generateSchoolCollage($uploaded_files, $upload_dir, $emis_code, $conn, $school_name, $primary_photo_id) {
    try {
        $collage = imagecreatetruecolor(COLLAGE_WIDTH, COLLAGE_HEIGHT);
        if (!$collage) throw new Exception("Failed to create collage canvas");
        
        for ($i = 0; $i < COLLAGE_HEIGHT; $i++) {
            $r = 240 - ($i / COLLAGE_HEIGHT * 10);
            $g = 248 - ($i / COLLAGE_HEIGHT * 8);
            $b = 255 - ($i / COLLAGE_HEIGHT * 5);
            $color = imagecolorallocate($collage, (int)$r, (int)$g, (int)$b);
            imageline($collage, 0, $i, COLLAGE_WIDTH, $i, $color);
        }
        
        $overlay = imagecolorallocatealpha($collage, 255, 255, 255, 60);
        imagefilledrectangle($collage, 0, 0, COLLAGE_WIDTH, COLLAGE_HEIGHT, $overlay);
        
        $priority = unserialize(PHOTO_PRIORITY);
        usort($uploaded_files, function($a, $b) use ($priority) {
            $a_val = $priority[$a['type']] ?? 6;
            $b_val = $priority[$b['type']] ?? 6;
            return $a_val - $b_val;
        });
        
        $layout = calculateOptimalLayout(count($uploaded_files));
        foreach ($uploaded_files as $index => $photo) {
            if ($index >= count($layout)) break;
            addPhotoToCollage($collage, $photo, $layout[$index], $upload_dir);
        }
        
        addHeaderBanner($collage, $school_name);
        addFooter($collage);
        addDecorativeBorder($collage);
        
        $filename = "collage_" . date('Ymd_His') . "_" . uniqid() . ".jpg";
        $filepath = $upload_dir . $filename;
        
        if (!imagejpeg($collage, $filepath, COLLAGE_QUALITY)) {
            throw new Exception("Failed to save collage image");
        }
        imagedestroy($collage);
        
        $photo_count = count($uploaded_files);
        
        $delete_stmt = $conn->prepare("DELETE FROM school_collages WHERE emis_code = ?");
        if ($delete_stmt) {
            $delete_stmt->bind_param("s", $emis_code);
            $delete_stmt->execute();
            $delete_stmt->close();
        }
        
        $stmt = $conn->prepare("
            INSERT INTO school_collages 
            (school_photos_id, emis_code, collage_filename, collage_width, collage_height, photo_count, generated_at)
            VALUES (?, ?, ?, ?, ?, ?, NOW())
        ");
        if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);
        
        $collage_w = COLLAGE_WIDTH;
        $collage_h = COLLAGE_HEIGHT;
        
        $stmt->bind_param("isssii", 
            $primary_photo_id,
            $emis_code,
            $filename,
            $collage_w,
            $collage_h,
            $photo_count
        );
        
        if (!$stmt->execute()) throw new Exception("Failed to save collage: " . $stmt->error);
        $stmt->close();
        
        logError("Collage saved", ['emis_code' => $emis_code, 'filename' => $filename]);
        return $filename;
        
    } catch (Exception $e) {
        logError("Collage error: " . $e->getMessage(), ['emis_code' => $emis_code]);
        return null;
    }
}

function addPhotoToCollage($collage, $photo, $pos, $upload_dir) {
    $photo_path = createThumbnail($photo['path'], THUMBNAIL_MAX_DIM);
    $photo_info = @getimagesize($photo_path);
    if (!$photo_info) return;
    
    $source = loadImage($photo_path, $photo_info[2]);
    if (!$source) return;
    
    $orig_width = imagesx($source);
    $orig_height = imagesy($source);
    
    $dest_x = (int)(COLLAGE_WIDTH * $pos['x']);
    $dest_y = (int)(COLLAGE_HEIGHT * $pos['y']);
    $dest_width = (int)(COLLAGE_WIDTH * $pos['width']);
    $dest_height = (int)(COLLAGE_HEIGHT * $pos['height']);
    
    $src_ratio = $orig_width / $orig_height;
    $dest_ratio = $dest_width / $dest_height;
    
    if ($src_ratio > $dest_ratio) {
        $src_height = $orig_height;
        $src_width = (int)($orig_height * $dest_ratio);
        $src_x = (int)(($orig_width - $src_width) / 2);
        $src_y = 0;
    } else {
        $src_width = $orig_width;
        $src_height = (int)($orig_width / $dest_ratio);
        $src_x = 0;
        $src_y = (int)(($orig_height - $src_height) / 2);
    }
    
    $temp = imagecreatetruecolor($dest_width, $dest_height);
    $transparent = imagecolorallocatealpha($temp, 0, 0, 0, 127);
    imagefill($temp, 0, 0, $transparent);
    imagealphablending($temp, false);
    imagesavealpha($temp, true);
    
    imagecopyresampled($temp, $source, 0, 0, $src_x, $src_y, $dest_width, $dest_height, $src_width, $src_height);
    applyRoundedCorners($temp, 15);
    imagecopy($collage, $temp, $dest_x, $dest_y, 0, 0, $dest_width, $dest_height);
    addPhotoLabel($collage, $photo['type'], $dest_x, $dest_y, $dest_width, $dest_height);
    
    imagedestroy($source);
    imagedestroy($temp);
    
    if ($photo_path !== $photo['path'] && file_exists($photo_path)) @unlink($photo_path);
}

function applyRoundedCorners(&$image, $radius) {
    $width = imagesx($image);
    $height = imagesy($image);
    
    $mask = imagecreatetruecolor($width, $height);
    $black = imagecolorallocate($mask, 0, 0, 0);
    $white = imagecolorallocate($mask, 255, 255, 255);
    
    imagefill($mask, 0, 0, $black);
    imagefilledrectangle($mask, $radius, 0, $width - $radius, $height, $white);
    imagefilledrectangle($mask, 0, $radius, $width, $height - $radius, $white);
    imagefilledellipse($mask, $radius, $radius, $radius * 2, $radius * 2, $white);
    imagefilledellipse($mask, $width - $radius, $radius, $radius * 2, $radius * 2, $white);
    imagefilledellipse($mask, $radius, $height - $radius, $radius * 2, $radius * 2, $white);
    imagefilledellipse($mask, $width - $radius, $height - $radius, $radius * 2, $radius * 2, $white);
    
    for ($x = 0; $x < $width; $x++) {
        for ($y = 0; $y < $height; $y++) {
            $mask_pixel = imagecolorsforindex($mask, imagecolorat($mask, $x, $y));
            if ($mask_pixel['red'] == 0) {
                imagesetpixel($image, $x, $y, imagecolorallocatealpha($image, 0, 0, 0, 127));
            }
        }
    }
    imagedestroy($mask);
}

function addPhotoLabel($image, $type, $x, $y, $width, $height) {
    $photo_types = unserialize(PHOTO_TYPES);
    $label_text = $photo_types[$type] ?? ucwords(str_replace('_', ' ', $type));
    
    $text_color = imagecolorallocate($image, 255, 255, 255);
    $bg_color = imagecolorallocatealpha($image, 0, 0, 0, 80);
    
    $text_width = imagefontwidth(3) * strlen($label_text) + 10;
    $text_height = imagefontheight(3) + 4;
    
    imagefilledrectangle($image, $x + 10, $y + $height - $text_height - 10, $x + 10 + $text_width, $y + $height - 5, $bg_color);
    imagestring($image, 3, $x + 15, $y + $height - $text_height - 5, $label_text, $text_color);
}

function addHeaderBanner($image, $school_name) {
    $banner_color = imagecolorallocatealpha($image, 52, 152, 219, 60);
    imagefilledrectangle($image, 0, 0, COLLAGE_WIDTH, 80, $banner_color);
    
    $text_color = imagecolorallocate($image, 255, 255, 255);
    
    $title = "SCHOOL PHOTO COLLAGE";
    $title_width = imagefontwidth(5) * strlen($title);
    $title_x = (int)((COLLAGE_WIDTH - $title_width) / 2);
    imagestring($image, 5, $title_x, 25, $title, $text_color);
    
    $school_name_trunc = (strlen($school_name) > 40) ? substr($school_name, 0, 40) . '...' : $school_name;
    $school_width = imagefontwidth(3) * strlen($school_name_trunc);
    $school_x = (int)((COLLAGE_WIDTH - $school_width) / 2);
    imagestring($image, 3, $school_x, 52, $school_name_trunc, $text_color);
}

function addFooter($image) {
    $footer_color = imagecolorallocatealpha($image, 44, 62, 80, 100);
    imagefilledrectangle($image, 0, COLLAGE_HEIGHT - 40, COLLAGE_WIDTH, COLLAGE_HEIGHT, $footer_color);
    
    $text_color = imagecolorallocate($image, 255, 255, 255);
    
    $date_text = "Generated: " . date('F j, Y g:i A');
    imagestring($image, 2, 20, COLLAGE_HEIGHT - 30, $date_text, $text_color);
    
    $copyright = "© School Management System " . date('Y');
    $copyright_width = imagefontwidth(2) * strlen($copyright);
    imagestring($image, 2, COLLAGE_WIDTH - $copyright_width - 20, COLLAGE_HEIGHT - 30, $copyright, $text_color);
}

function addDecorativeBorder($image) {
    $border_color = imagecolorallocate($image, 52, 152, 219);
    $shadow_color = imagecolorallocate($image, 44, 62, 80);
    
    imagerectangle($image, 3, 3, COLLAGE_WIDTH - 4, COLLAGE_HEIGHT - 4, $shadow_color);
    imagerectangle($image, 0, 0, COLLAGE_WIDTH - 1, COLLAGE_HEIGHT - 1, $border_color);
    imagerectangle($image, 1, 1, COLLAGE_WIDTH - 2, COLLAGE_HEIGHT - 2, $border_color);
}

function notifyAdmin($subject, $message, $school_name, $emis_code) {
    $admin_email = 'admin@example.com';
    $headers = "From: School Management System <noreply@schoolsystem.com>\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $body = "School: {$school_name} (EMIS: {$emis_code})\nError: {$message}\nTime: " . date('Y-m-d H:i:s') . "\n";
    @mail($admin_email, $subject, $body, $headers);
}

// ============================================================================
// MAIN PROCESSING
// ============================================================================
$success_message = '';
$error_message = '';
$uploaded_files = [];

if (!isset($_SESSION['school_name']) || !isset($_SESSION['emis_code'])) {
    header("Location: login.php");
    exit();
}

$school_name = get_session_value('school_name', '');
$emis_code = get_session_value('emis_code', '');

$upload_dir = UPLOAD_BASE_PATH . "{$emis_code}/";
if (!file_exists($upload_dir)) mkdir($upload_dir, 0755, true);

// Process the form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error_message = "Security validation failed. Please try again.";
        $_SESSION['error_message'] = $error_message;
        header("Location: school_step10.php");
        exit;
    } else {
        $is_valid = true;
        $uploaded_files = [];
        $photo_types_list = unserialize(PHOTO_TYPES);
        $required_types_list = unserialize(REQUIRED_TYPES);
        $valid_enum_types = ['entrance', 'building', 'playground', 'assembly', 'labs'];
        $required_types = [];
        $optional_types = [];
        
        foreach ($photo_types_list as $type => $label) {
            if (in_array($type, $valid_enum_types)) {
                if (in_array($type, $required_types_list)) $required_types[$type] = $label;
                else $optional_types[$type] = $label;
            }
        }
        
        if (isset($_FILES['school_photos']) && !empty($_FILES['school_photos']['tmp_name'][0])) {
            // Delete old photos first
            deleteOldPhotosAndCollage($conn, $emis_code, $upload_dir);
            
            foreach ($_FILES['school_photos']['tmp_name'] as $index => $tmp_name) {
                if (empty($tmp_name)) continue;
                
                $photo_type = $_POST['photo_types'][$index] ?? '';
                if (!in_array($photo_type, $valid_enum_types)) {
                    $error_message = "Invalid photo type selected.";
                    $is_valid = false;
                    break;
                }
                
                $file_name = basename($_FILES['school_photos']['name'][$index]);
                $file_type = $_FILES['school_photos']['type'][$index];
                $file_size = $_FILES['school_photos']['size'][$index];
                $file_error = $_FILES['school_photos']['error'][$index];
                
                if ($file_error !== UPLOAD_ERR_OK) {
                    if ($file_error !== UPLOAD_ERR_NO_FILE) {
                        $error_message = "Upload error: " . $file_error;
                        $is_valid = false;
                    }
                    continue;
                }
                
                if ($file_size > MAX_FILE_SIZE) {
                    $type_label = $photo_types_list[$photo_type] ?? 'Photo';
                    $error_message = "File too large for {$type_label}. Maximum size is 5MB.";
                    $is_valid = false;
                    break;
                }
                
                $allowed_types = unserialize(ALLOWED_MIME_TYPES);
                if (!in_array($file_type, $allowed_types)) {
                    $type_label = $photo_types_list[$photo_type] ?? 'Photo';
                    $error_message = "Invalid file type for {$type_label}.";
                    $is_valid = false;
                    break;
                }
                
                $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
                $new_filename = "{$photo_type}_" . date('Ymd_His') . "_{$index}_" . uniqid() . ".{$file_extension}";
                $upload_path = $upload_dir . $new_filename;
                
                if (!move_uploaded_file($tmp_name, $upload_path)) {
                    $type_label = $photo_types_list[$photo_type] ?? 'Photo';
                    $error_message = "Failed to upload {$type_label}.";
                    $is_valid = false;
                    break;
                }
                
                if (!validateImageFile($upload_path)) {
                    $type_label = $photo_types_list[$photo_type] ?? 'Photo';
                    $error_message = "Invalid or corrupted image file for {$type_label}.";
                    $is_valid = false;
                    @unlink($upload_path);
                    break;
                }
                
                $upload_path = stripExifData($upload_path);
                optimizeImage($upload_path);
                
                $file_hash = md5_file($upload_path);
                if (empty($file_hash)) {
                    $error_message = "Failed to generate file hash.";
                    $is_valid = false;
                    @unlink($upload_path);
                    break;
                }
                
                // Check for duplicates in the NEW uploads only
                $check_stmt = $conn->prepare("SELECT id FROM school_photos WHERE emis_code = ? AND photo_hash = ?");
                if ($check_stmt) {
                    $check_stmt->bind_param("ss", $emis_code, $file_hash);
                    $check_stmt->execute();
                    if ($check_stmt->get_result()->num_rows > 0) {
                        $type_label = $photo_types_list[$photo_type] ?? 'Photo';
                        $error_message = "This {$type_label} photo has already been uploaded.";
                        $is_valid = false;
                        @unlink($upload_path);
                        $check_stmt->close();
                        break;
                    }
                    $check_stmt->close();
                }
                
                $description = isset($photo_types_list[$photo_type]) ? substr($photo_types_list[$photo_type], 0, 100) : 'School Photo';
                $uploaded_files[] = [
                    'type' => $photo_type,
                    'filename' => $new_filename,
                    'path' => $upload_path,
                    'description' => $description,
                    'hash' => $file_hash
                ];
            }
            
            if ($is_valid) {
                $uploaded_types = array_column($uploaded_files, 'type');
                $missing_required = array_diff(array_keys($required_types), $uploaded_types);
                
                if (!empty($missing_required)) {
                    $missing_names = array_map(fn($t) => $required_types[$t], $missing_required);
                    $error_message = "Missing required photos: " . implode(', ', $missing_names);
                    $is_valid = false;
                } elseif (count($uploaded_files) < MIN_PHOTOS) {
                    $error_message = "Minimum " . MIN_PHOTOS . " new photos required. You uploaded " . count($uploaded_files) . ".";
                    $is_valid = false;
                } elseif (count($uploaded_files) > MAX_PHOTOS) {
                    $error_message = "Maximum " . MAX_PHOTOS . " photos allowed. You uploaded " . count($uploaded_files) . ".";
                    $is_valid = false;
                }
            }
            
            if ($is_valid && !empty($uploaded_files)) {
                try {
                    $conn->begin_transaction();
                    $primary_photo_id = null;
                    
                    foreach ($uploaded_files as $photo) {
                        $stmt = $conn->prepare("INSERT INTO school_photos (emis_code, photo_type, file_path, photo_hash, description, uploaded_at) VALUES (?, ?, ?, ?, ?, NOW())");
                        if ($stmt) {
                            $stmt->bind_param("sssss", $emis_code, $photo['type'], $photo['filename'], $photo['hash'], $photo['description']);
                            if (!$stmt->execute()) throw new Exception("Failed to save photo: " . $stmt->error);
                            if ($primary_photo_id === null) $primary_photo_id = $conn->insert_id;
                            $stmt->close();
                        }
                    }
                    
                    if ($primary_photo_id === null) throw new Exception("No photos were saved");
                    
                    $collage_filename = generateSchoolCollage($uploaded_files, $upload_dir, $emis_code, $conn, $school_name, $primary_photo_id);
                    
                    if ($collage_filename) {
                        $conn->commit();
                        $success_message = "School photos updated successfully! Saved " . count($uploaded_files) . " new photos and generated a collage.";
                        $_SESSION['success_message'] = $success_message;
                        header("Location: school_step10.php");
                        exit();
                    } else {
                        throw new Exception("Collage generation failed");
                    }
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $error_message = "An error occurred: " . $e->getMessage();
                    logError("Photo upload error: " . $e->getMessage(), ['emis_code' => $emis_code, 'school_name' => $school_name]);
                    
                    // Clean up uploaded files
                    foreach ($uploaded_files as $photo) {
                        if (file_exists($photo['path'])) @unlink($photo['path']);
                    }
                    
                    $_SESSION['error_message'] = $error_message;
                    header("Location: school_step10.php");
                    exit();
                }
            } else {
                $_SESSION['error_message'] = $error_message;
                $_SESSION['form_data'] = $_POST;
                header("Location: school_step10.php");
                exit();
            }
        } else {
            $error_message = "Please select at least " . MIN_PHOTOS . " new photos to upload.";
            $_SESSION['error_message'] = $error_message;
            header("Location: school_step10.php");
            exit();
        }
    }
} else {
    // Not a POST request - redirect to form
    header("Location: school_step10.php");
    exit();
}
?>