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

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

// School Profile Completion Check
require_once 'school_profile_completion_check.php';

// Database connection
include_once 'connect.php';

// Initialize variables
$success_message = '';
$error_message = '';

// Retrieve session variables
$school_name = $_SESSION['school_name'] ?? '';
$emis_code = $_SESSION['emis_code'] ?? '';
$cate_id = $_SESSION['cate_id'] ?? '';
$level_id = $_SESSION['level_id'] ?? '';

error_log("EMIS Code from session: " . $emis_code);

// Check if emis_code exists
if (empty($emis_code)) {
    error_log("EMIS code is empty in session");
    $_SESSION['error_message'] = "EMIS code not found in session. Please login again.";
    header("Location: login.php");
    exit;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['school_building_submit'])) {
    $form_data = [
        'building_select' => $_POST['building_select'] ?? '',
        'ownershiptype' => $_POST['ownershiptype'] ?? '',
        'rental_payee' => trim($_POST['rental_payee'] ?? ''),
        'construction_year' => trim($_POST['construction_year'] ?? ''),
        'building_condition' => $_POST['building_condition'] ?? '',
        'cons_material' => $_POST['cons_material'] ?? '',
        'boundry_wall' => $_POST['boundry_wall'] ?? '',
        'nobuilding_reason' => trim($_POST['nobuilding_reason'] ?? ''),
        'room_type' => $_POST['room_type'] ?? [],
        'total_rooms' => $_POST['total_rooms'] ?? [],
        'room_condition' => $_POST['room_condition'] ?? []
    ];
    
    $building_available = ($form_data['building_select'] === 'yes');
    $no_building = ($form_data['building_select'] === 'no');
    $errors = [];
    
    // Validation
    if (empty($form_data['building_select'])) {
        $errors[] = 'Please select building availability';
    }
    
    if ($building_available) {
        if (empty($form_data['ownershiptype'])) $errors[] = 'Ownership Status is required';
        if (empty($form_data['construction_year'])) {
            $errors[] = 'Construction Year is required';
        } elseif (!preg_match('/^\d{4}$/', $form_data['construction_year'])) {
            $errors[] = 'Construction Year must be a valid 4-digit year';
        } else {
            $year = intval($form_data['construction_year']);
            $current_year = date('Y');
            if ($year < 1901 || $year > $current_year) {
                $errors[] = "Construction Year must be between 1901 and {$current_year}";
            }
        }
        if (empty($form_data['building_condition'])) $errors[] = 'Building Condition is required';
        if (empty($form_data['cons_material'])) $errors[] = 'Construction Material is required';
        if (empty($form_data['boundry_wall'])) $errors[] = 'Boundary Wall information is required';
        
        $room_errors = [];
        $room_count = count($form_data['room_type']);
        if ($room_count === 0) {
            $errors[] = 'At least one room detail entry is required';
        } else {
            $used_room_types = [];
            $valid_room_count = 0;
            for ($i = 0; $i < $room_count; $i++) {
                $room_type = $form_data['room_type'][$i] ?? '';
                $total_rooms = $form_data['total_rooms'][$i] ?? '';
                $room_condition = $form_data['room_condition'][$i] ?? '';
                
                if (empty($room_type) && empty($total_rooms) && empty($room_condition)) continue;
                $valid_room_count++;
                
                if (empty($room_type)) {
                    $room_errors[] = "Room type required for entry #" . ($i + 1);
                } elseif (in_array($room_type, $used_room_types)) {
                    $room_errors[] = "Room type already used. Each type can only be selected once.";
                } else {
                    $used_room_types[] = $room_type;
                }
                if (empty($total_rooms) || !is_numeric($total_rooms) || intval($total_rooms) < 0) {
                    $room_errors[] = "Valid room count required for entry #" . ($i + 1);
                }
                if (empty($room_condition)) {
                    $room_errors[] = "Room condition required for entry #" . ($i + 1);
                }
            }
            
            if ($valid_room_count === 0) {
                $errors[] = 'At least one valid room detail is required';
            }
            if (!empty($room_errors)) {
                $errors = array_merge($errors, $room_errors);
            }
        }
    } elseif ($no_building) {
        if (empty($form_data['nobuilding_reason'])) {
            $errors[] = 'Reason for no building is required';
        } elseif (strlen($form_data['nobuilding_reason']) < 10) {
            $errors[] = 'Reason must be at least 10 characters long';
        }
    }
    
    if (empty($errors)) {
        try {
            // =================== PREPARE VALUES ===================
            if ($no_building) {
                $building_select_val = 'no';
                $nobuilding_reason = !empty($form_data['nobuilding_reason']) ? $form_data['nobuilding_reason'] : '';
                // ✅ CRITICAL FIX: Set NULL variables BEFORE bind_param
                $ownershiptype_null = null;
                $rental_payee_null = null;
                $construction_year_null = null;
                $building_condition_null = null;
                $cons_material_null = null;
                $boundry_wall_null = null;
            } else {
                $building_select_val = 'yes';
                $ownershiptype = !empty($form_data['ownershiptype']) ? intval($form_data['ownershiptype']) : null;
                $rental_payee = !empty($form_data['rental_payee']) ? $form_data['rental_payee'] : null;
                $construction_year = !empty($form_data['construction_year']) ? intval($form_data['construction_year']) : null;
                $building_condition = !empty($form_data['building_condition']) ? $form_data['building_condition'] : null;
                $cons_material = !empty($form_data['cons_material']) ? intval($form_data['cons_material']) : null;
                $boundry_wall = !empty($form_data['boundry_wall']) ? $form_data['boundry_wall'] : null;
                $nobuilding_reason = null;
            }
            // =================== END PREPARE VALUES ===================
            
            // =================== INSERT/UPDATE BUILDING ===================
            $sql = "INSERT INTO school_building (
                emis_code, building_select, ownershiptype, rental_payee,
                construction_year, building_condition, cons_material, boundry_wall,
                nobuilding_reason, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ON DUPLICATE KEY UPDATE
                building_select = VALUES(building_select),
                ownershiptype = VALUES(ownershiptype),
                rental_payee = VALUES(rental_payee),
                construction_year = VALUES(construction_year),
                building_condition = VALUES(building_condition),
                cons_material = VALUES(cons_material),
                boundry_wall = VALUES(boundry_wall),
                nobuilding_reason = VALUES(nobuilding_reason),
                updated_at = NOW()";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Database preparation error: " . $conn->error);
            }
            
            if ($no_building) {
                // ✅ NULL variables already set ABOVE (critical fix)
                $stmt->bind_param(
                    "sssssssss",
                    $emis_code,
                    $building_select_val,
                    $ownershiptype_null,
                    $rental_payee_null,
                    $construction_year_null,
                    $building_condition_null,
                    $cons_material_null,
                    $boundry_wall_null,
                    $nobuilding_reason
                );
            } else {
                $stmt->bind_param(
                    "ssisisiss",
                    $emis_code,
                    $building_select_val,
                    $ownershiptype,
                    $rental_payee,
                    $construction_year,
                    $building_condition,
                    $cons_material,
                    $boundry_wall,
                    $nobuilding_reason
                );
            }
            
            if (!$stmt->execute()) {
                throw new Exception("Error saving building: " . $stmt->error);
            }
            $stmt->close();
            // =================== END INSERT/UPDATE BUILDING ===================
            
            // =================== GET BUILDING ID (PRIMARY KEY) ===================
            $get_bid_sql = "SELECT id FROM school_building WHERE emis_code = ?";
            $get_bid_stmt = $conn->prepare($get_bid_sql);
            $get_bid_stmt->bind_param("s", $emis_code);
            $get_bid_stmt->execute();
            $bid_result = $get_bid_stmt->get_result();
            if ($bid_result->num_rows === 0) {
                throw new Exception("Building record not found after save. Please retry.");
            }
            $building_id = $bid_result->fetch_assoc()['id']; // Get primary key 'id'
            $get_bid_stmt->close();
            // =================== END GET BUILDING ID ===================
            
            // =================== HANDLE ROOMS (SIMPLE DELETE ALL + INSERT NEW) ===================
            $conn->begin_transaction();
            try {
                // ALWAYS delete existing rooms for this building (works for insert AND update)
                $del_stmt = $conn->prepare("DELETE FROM building_rooms_details WHERE building_id = ?");
                $del_stmt->bind_param("i", $building_id);
                if (!$del_stmt->execute()) {
                    throw new Exception("Room cleanup failed: " . $del_stmt->error);
                }
                $del_stmt->close();
                
                // ONLY insert rooms if building is available
                if ($building_available) {
                    $valid_rooms = [];
                    $room_count = count($form_data['room_type']);
                    for ($i = 0; $i < $room_count; $i++) {
                        $rt = trim($form_data['room_type'][$i] ?? '');
                        $tr = trim($form_data['total_rooms'][$i] ?? '0');
                        $rc = trim($form_data['room_condition'][$i] ?? '');
                        if (empty($rt) && empty($tr) && empty($rc)) continue;
                        $valid_rooms[] = [
                            'room_type' => intval($rt),
                            'total_rooms' => intval($tr),
                            'room_condition' => $rc
                        ];
                    }
                    
                    if (!empty($valid_rooms)) {
                        $ins_stmt = $conn->prepare(
                            "INSERT INTO building_rooms_details (building_id, room_type, total_rooms, room_condition, created_at, updated_at) 
                             VALUES (?, ?, ?, ?, NOW(), NOW())"
                        );
                        $ins_stmt->bind_param("iiis", $bid, $rtype, $trooms, $rcond);
                        foreach ($valid_rooms as $room) {
                            $bid = $building_id;
                            $rtype = $room['room_type'];
                            $trooms = $room['total_rooms'];
                            $rcond = $room['room_condition'];
                            if (!$ins_stmt->execute()) {
                                throw new Exception("Room insert failed: " . $ins_stmt->error);
                            }
                        }
                        $ins_stmt->close();
                    }
                }
                // If no_building: rooms already deleted above (nothing to insert)
                $conn->commit();
            } catch (Exception $e) {
                $conn->rollback();
                throw $e;
            }
            // =================== END HANDLE ROOMS ===================
            
            // Cleanup and redirect
            unset($_SESSION['form_data'], $_SESSION['error_message']);
            $_SESSION['success_message'] = "School building information saved successfully!";
            header("Location: school_step4.php");
            exit();
            
        } catch (Exception $e) {
            error_log("School Step 3 Save Error: " . $e->getMessage());
            $_SESSION['error_message'] = "Error saving data: " . htmlspecialchars($e->getMessage());
            $_SESSION['form_data'] = $form_data;
            header("Location: school_step3.php");
            exit();
        }
    } else {
        $_SESSION['error_message'] = implode("<br>", $errors);
        $_SESSION['form_data'] = $form_data;
        header("Location: school_step3.php");
        exit();
    }
} else {
    header("Location: school_step3.php");
    exit;
}
?>