<?php
// school_step4_save.php
// Session started
require_once 'session_config_school.php';

// Validate school session
if (!validateSchoolSession()) {
    header("Location: login.php");
    exit;
}

// Database connection
include_once 'connect.php';

// Initialize response variables
$errors = [];
$success = false;

// 🔒 SECURITY: Verify CSRF token
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method.";
    header("Location: school_step4.php");
    exit;
}

// Check CSRF token
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    $_SESSION['error_message'] = "Security validation failed. Please try again.";
    header("Location: school_step4.php");
    exit;
}

// Get session variables
$emis_code = $_SESSION['emis_code'] ?? '';
$school_name = $_SESSION['school_name'] ?? '';

if (empty($emis_code)) {
    $_SESSION['error_message'] = "School session expired. Please login again.";
    header("Location: login.php");
    exit;
}

// =================== VALIDATION FUNCTIONS ===================

/**
 * Validate and sanitize YES/NO fields
 */
function validateYesNo($value, $field_name) {
    $value = strtoupper(trim($value));
    if (!in_array($value, ['YES', 'NO'])) {
        return [false, "$field_name must be either YES or NO"];
    }
    return [true, $value];
}

/**
 * Validate integer within range
 */
function validateInteger($value, $field_name, $min, $max) {
    if (!is_numeric($value)) {
        return [false, "$field_name must be a number"];
    }
    $num = intval($value);
    if ($num < $min || $num > $max) {
        return [false, "$field_name must be between $min and $max"];
    }
    return [true, $num];
}

/**
 * Validate lab type
 */
function validateLabType($lab_type) {
    $valid_lab_types = [
        'computer', 'physics', 'combined', 'zoology', 'botany', 
        'home_economics', 'technical', 'smart', 'ece', 'sports',
        'language', 'math', 'art_craft', 'music', 'library',
        'chemistry', 'biology', 'env_science'
    ];
    return in_array($lab_type, $valid_lab_types);
}

// =================== VALIDATE BASIC FACILITIES ===================

// Basic facilities mapping (form field => database column)
$basic_fields = [
    'electricity' => 'electricity',
    'water' => 'water',
    'internet' => 'internet',
    'road' => 'road',
    'assembly' => 'assembly_ground',
    'ground' => 'play_ground',
    'medical' => 'medical_facility',
    'gas' => 'gas_supply',
    'ptransport' => 'public_transport'
];

$facilities_data = [];

foreach ($basic_fields as $form_field => $db_field) {
    if (!isset($_POST[$form_field])) {
        $errors[] = "Missing value for " . str_replace('_', ' ', $form_field);
        continue;
    }
    
    list($valid, $result) = validateYesNo($_POST[$form_field], $form_field);
    if (!$valid) {
        $errors[] = $result;
    } else {
        $facilities_data[$db_field] = $result;
    }
}

// =================== VALIDATE FURNITURE FACILITIES ===================

$furniture_fields = [
    'schair' => ['staff_chairs', 0, 1000],
    'stable' => ['staff_tables', 0, 1000],
    'desk' => ['student_desks', 0, 10000],
    'cupboard' => ['cupboards', 0, 1000],
    'board' => ['writing_boards', 0, 1000],
    'dice' => ['podiums', 0, 1000]
];

foreach ($furniture_fields as $form_field => [$db_field, $min, $max]) {
    if (!isset($_POST[$form_field]) || $_POST[$form_field] === '') {
        $errors[] = "Missing value for " . str_replace('_', ' ', $form_field);
        continue;
    }
    
    list($valid, $result) = validateInteger($_POST[$form_field], $form_field, $min, $max);
    if (!$valid) {
        $errors[] = $result;
    } else {
        $facilities_data[$db_field] = $result;
    }
}

// =================== COLLECT LAB DATA ===================

$lab_data = [];
$lab_pattern = '/^(equip_|req_)(.+)$/';

foreach ($_POST as $key => $value) {
    if (preg_match($lab_pattern, $key, $matches)) {
        $type = $matches[1]; // 'equip_' or 'req_'
        $lab_type = $matches[2]; // lab type
        
        if (!validateLabType($lab_type)) {
            $errors[] = "Invalid lab type: " . htmlspecialchars($lab_type);
            continue;
        }
        
        if (!isset($lab_data[$lab_type])) {
            $lab_data[$lab_type] = [];
        }
        
        if ($type === 'equip_') {
            // Validate equipment value
            list($valid, $equip_value) = validateYesNo($value, "Lab equipment for $lab_type");
            if (!$valid) {
                $errors[] = $equip_value;
            } else {
                $lab_data[$lab_type]['equipment_available'] = $equip_value;
            }
        } else { // req_
            $lab_data[$lab_type]['requirements'] = trim($value);
        }
    }
}

// Validate that each lab has equipment selection
foreach ($lab_data as $lab_type => $data) {
    if (!isset($data['equipment_available'])) {
        $errors[] = "Equipment availability is required for " . ucfirst(str_replace('_', ' ', $lab_type)) . " lab";
    }
}

// =================== PROCESS IF NO ERRORS ===================

if (empty($errors)) {
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        // 1. Check if facilities record exists
        $stmt = $conn->prepare("SELECT id FROM school_facilities WHERE emis_code = ?");
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $result = $stmt->get_result();
        $facility_exists = $result->num_rows > 0;
        
        if ($facility_exists) {
            $facility_row = $result->fetch_assoc();
            $facility_id = $facility_row['id'];
            
            // Update existing facilities record
            $update_fields = [];
            $update_values = [];
            $update_types = "";
            
            foreach ($facilities_data as $field => $value) {
                $update_fields[] = "`$field` = ?";
                $update_values[] = $value;
                $update_types .= is_numeric($value) ? "i" : "s";
            }
            
            // Add updated_at to the update
            $update_fields[] = "updated_at = CURRENT_TIMESTAMP";
            
            $update_sql = "UPDATE school_facilities SET " . implode(", ", $update_fields) . " WHERE emis_code = ?";
            $update_values[] = $emis_code;
            $update_types .= "s";
            
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param($update_types, ...$update_values);
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to update facilities: " . $stmt->error);
            }
            $stmt->close();
            
        } else {
            // Insert new facilities record
            $columns = array_merge(['emis_code'], array_keys($facilities_data));
            $placeholders = array_fill(0, count($columns), '?');
            $values = array_merge([$emis_code], array_values($facilities_data));
            
            $insert_sql = "INSERT INTO school_facilities (`" . implode("`, `", $columns) . "`) VALUES (" . implode(", ", $placeholders) . ")";
            
            // Determine types
            $types = "s"; // emis_code is string
            foreach (array_values($facilities_data) as $val) {
                $types .= is_numeric($val) ? "i" : "s";
            }
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param($types, ...$values);
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to insert facilities: " . $stmt->error);
            }
            
            $facility_id = $stmt->insert_id;
            $stmt->close();
        }
        
        // 2. Process labs if facility_id exists
        if (!empty($facility_id)) {
            // Get existing labs for this facility
            $existing_labs = [];
            $stmt = $conn->prepare("SELECT lab_type FROM school_labs WHERE facility_id = ?");
            $stmt->bind_param("i", $facility_id);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $existing_labs[$row['lab_type']] = true;
            }
            $stmt->close();
            
            // Process each lab from form
            foreach ($lab_data as $lab_type => $data) {
                $equipment = $data['equipment_available'];
                $requirements = $data['requirements'] ?? null;
                
                if (isset($existing_labs[$lab_type])) {
                    // Update existing lab
                    $stmt = $conn->prepare("UPDATE school_labs SET equipment_available = ?, requirements = ? WHERE facility_id = ? AND lab_type = ?");
                    $stmt->bind_param("ssis", $equipment, $requirements, $facility_id, $lab_type);
                    
                    if (!$stmt->execute()) {
                        throw new Exception("Failed to update lab: $lab_type");
                    }
                    $stmt->close();
                    
                    // Remove from existing_labs array (to track what's left for deletion)
                    unset($existing_labs[$lab_type]);
                    
                } else {
                    // Insert new lab
                    $stmt = $conn->prepare("INSERT INTO school_labs (facility_id, lab_type, equipment_available, requirements) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("isss", $facility_id, $lab_type, $equipment, $requirements);
                    
                    if (!$stmt->execute()) {
                        throw new Exception("Failed to insert lab: $lab_type");
                    }
                    $stmt->close();
                }
            }
            
            // Delete labs that were removed from form
            foreach (array_keys($existing_labs) as $lab_to_delete) {
                $stmt = $conn->prepare("DELETE FROM school_labs WHERE facility_id = ? AND lab_type = ?");
                $stmt->bind_param("is", $facility_id, $lab_to_delete);
                
                if (!$stmt->execute()) {
                    throw new Exception("Failed to delete lab: $lab_to_delete");
                }
                $stmt->close();
            }
        }
        
        // Commit transaction
        $conn->commit();
        
        // Set success message
        $_SESSION['success_message'] = "Facilities information saved successfully!";
        
        // Determine next step based on school category/level if needed
        $next_step = "school_step5.php"; // Default next step
        
        // You can add logic here to determine next step based on school type
        // For example:
        // if ($cate_id == 'some_value') {
        //     $next_step = "school_step5_special.php";
        // }
        
        header("Location: $next_step");
        exit;
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        $errors[] = "Database error: " . $e->getMessage();
        
        // Log error for debugging
        error_log("School Step4 Save Error: " . $e->getMessage());
    }
}

// =================== HANDLE ERRORS ===================

// If we reach here, there were errors
$_SESSION['error_message'] = implode("\\n", $errors);

// Preserve form data for repopulation
$_SESSION['form_data'] = [];
foreach ($_POST as $key => $value) {
    if ($key !== 'csrf_token') { // Don't preserve CSRF token
        $_SESSION['form_data'][$key] = $value;
    }
}

// Redirect back to form
header("Location: school_step4.php");
exit;
?>