<?php
// Start session and validate
require_once 'session_config_school.php';

// Validate session
if (!validateSchoolSession()) {
    $response = [
        'success' => false,
        'message' => "Session validation failed",
        'redirect' => "login.php"
    ];
    echo json_encode($response);
    exit();
}

// Check if user is logged in
if (!isset($_SESSION['emis_code'])) {
    $response = [
        'success' => false,
        'message' => "No EMIS code in session",
        'redirect' => "login.php"
    ];
    echo json_encode($response);
    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'] ?? '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect and sanitize form data
    $form_data = [
        'land' => $_POST['land'] ?? '',
        'kanal' => trim($_POST['kanal'] ?? ''),
        'marla' => trim($_POST['marla'] ?? ''),
        'landtype' => $_POST['landtype'] ?? '',
        'ownershipstatus' => $_POST['ownershipstatus'] ?? '',
        'landdocument' => $_POST['landdocument'] ?? '',
        'land_under_school' => $_POST['land_under_school'] ?? '',
        'not_under_kanal' => trim($_POST['not_under_kanal'] ?? ''),
        'not_under_marla' => trim($_POST['not_under_marla'] ?? ''),
        'reason_not_under_control' => trim($_POST['reason_not_under_control'] ?? ''),
        'encroachment_details' => trim($_POST['encroachment_details'] ?? ''),
        'legal_issues' => $_POST['legal_issues'] ?? 'No',
        'legal_issue_type' => $_POST['legal_issue_type'] ?? '',
        'court_case_number' => trim($_POST['court_case_number'] ?? ''),
        'court_name' => trim($_POST['court_name'] ?? ''),
        'legal_issue_details' => trim($_POST['legal_issue_details'] ?? ''),
        'legal_status' => $_POST['legal_status'] ?? '',
        'noland' => trim($_POST['noland'] ?? '')
    ];

    // Determine land availability state
    $land_available = ($form_data['land'] === 'landyes') ? 'Yes' : 'No';
    $has_land = ($land_available === 'Yes');
    $all_under_control = ($form_data['land_under_school'] === 'Yes');
    $has_legal_issues = ($form_data['legal_issues'] === 'Yes');

    // Validate required fields
    $errors = [];
    
    if (empty($form_data['land'])) {
        $errors[] = 'Please select land availability (Land Available or No Land)';
    }
    
    if ($has_land) {
        // Validate land details
        if (empty($form_data['kanal']) || !is_numeric($form_data['kanal']) || $form_data['kanal'] < 0) {
            $errors[] = 'Valid Kanal value is required (must be a positive number)';
        }
        
        if (empty($form_data['landtype'])) {
            $errors[] = 'Land Type is required';
        }
        
        if (empty($form_data['ownershipstatus'])) {
            $errors[] = 'Ownership Status is required';
        }
        
        if (empty($form_data['landdocument'])) {
            $errors[] = 'Land Document availability is required';
        }
        
        if (empty($form_data['land_under_school'])) {
            $errors[] = 'Please select if all land is under school control';
        }
        
        // Validate marla range
        if ($form_data['marla'] !== '' && (!is_numeric($form_data['marla']) || $form_data['marla'] < 0 || $form_data['marla'] > 19)) {
            $errors[] = 'Marla must be between 0 and 19';
        }
        
        // Validate not-under-control values only when applicable
        if (!$all_under_control) {
            if ($form_data['not_under_kanal'] !== '' && (!is_numeric($form_data['not_under_kanal']) || $form_data['not_under_kanal'] < 0)) {
                $errors[] = 'Valid Kanal value required for land not under control';
            }
            
            if ($form_data['not_under_marla'] !== '' && (!is_numeric($form_data['not_under_marla']) || $form_data['not_under_marla'] < 0 || $form_data['not_under_marla'] > 19)) {
                $errors[] = 'Marla not under control must be between 0 and 19';
            }
            
            // Compare values only when both are provided
            if ($form_data['not_under_kanal'] !== '' && $form_data['kanal'] !== '' && 
                floatval($form_data['not_under_kanal']) > floatval($form_data['kanal'])) {
                $errors[] = 'Kanal not under control cannot be greater than total kanal';
            }
            
            if ($form_data['not_under_marla'] !== '' && $form_data['marla'] !== '' && 
                floatval($form_data['not_under_marla']) > floatval($form_data['marla'])) {
                $errors[] = 'Marla not under control cannot be greater than total marla';
            }
        }
    } else {
        // No land case
        if (empty($form_data['noland'])) {
            $errors[] = 'Reason for no land is required';
        }
    }

    if (empty($errors)) {
        try {
            // Prepare values for database
            // If no land is selected, set all land-related fields to NULL
            if (!$has_land) {
                $kanal = null;
                $marla = null;
                $land_type = null;
                $ownership_status = null;
                $land_document = null;
                $land_under_school = null;
                $land_not_under_school = null;
                $not_under_kanal = null;
                $not_under_marla = null;
                $reason_not_under_control = null;
                $encroachment_details = null;
                $legal_issues = null;
                $legal_issue_type = null;
                $court_case_number = null;
                $court_name = null;
                $legal_issue_details = null;
                $legal_status = null;
                $no_land_reason = $form_data['noland'];
            } else {
                // Land is available - process all fields
                $kanal = !empty($form_data['kanal']) ? intval($form_data['kanal']) : 0;
                $marla = !empty($form_data['marla']) ? intval($form_data['marla']) : 0;
                $land_type = $form_data['landtype'];
                $ownership_status = !empty($form_data['ownershipstatus']) ? intval($form_data['ownershipstatus']) : null;
                $land_document = $form_data['landdocument'];
                $land_under_school = $form_data['land_under_school'];
                $land_not_under_school = $all_under_control ? 'No' : 'Yes';
                $not_under_kanal = !empty($form_data['not_under_kanal']) ? intval($form_data['not_under_kanal']) : 0;
                $not_under_marla = !empty($form_data['not_under_marla']) ? intval($form_data['not_under_marla']) : 0;
                $reason_not_under_control = $form_data['reason_not_under_control'];
                $encroachment_details = $form_data['encroachment_details'];
                $legal_issues = $form_data['legal_issues'];
                $legal_issue_type = $form_data['legal_issue_type'];
                $court_case_number = $form_data['court_case_number'];
                $court_name = $form_data['court_name'];
                $legal_issue_details = $form_data['legal_issue_details'];
                $legal_status = $form_data['legal_status'];
                $no_land_reason = ''; // Clear no land reason when land is available
            }
            
            // Insert or update school_land table
            $sql = "INSERT INTO school_land (
                emis_code, land_available, kanal, marla, land_type,
                ownership_status, land_document, land_under_school,
                land_not_under_school, not_under_kanal, not_under_marla,
                reason_not_under_control, encroachment_details, legal_issues,
                legal_issue_type, court_case_number, court_name,
                legal_issue_details, legal_status, no_land_reason,
                created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ON DUPLICATE KEY UPDATE
                land_available = VALUES(land_available),
                kanal = VALUES(kanal),
                marla = VALUES(marla),
                land_type = VALUES(land_type),
                ownership_status = VALUES(ownership_status),
                land_document = VALUES(land_document),
                land_under_school = VALUES(land_under_school),
                land_not_under_school = VALUES(land_not_under_school),
                not_under_kanal = VALUES(not_under_kanal),
                not_under_marla = VALUES(not_under_marla),
                reason_not_under_control = VALUES(reason_not_under_control),
                encroachment_details = VALUES(encroachment_details),
                legal_issues = VALUES(legal_issues),
                legal_issue_type = VALUES(legal_issue_type),
                court_case_number = VALUES(court_case_number),
                court_name = VALUES(court_name),
                legal_issue_details = VALUES(legal_issue_details),
                legal_status = VALUES(legal_status),
                no_land_reason = VALUES(no_land_reason),
                updated_at = NOW()";
            
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Database preparation error: " . $conn->error);
            }
            
            // Bind parameters - handle NULL values properly
            // For integer fields, we need to bind with proper types
            if (!$has_land) {
                // Bind with NULL values for no land case
                $stmt->bind_param(
                    "ssiissssiiisssssssss",
                    $emis_code,
                    $land_available,
                    $kanal, // NULL
                    $marla, // NULL
                    $land_type, // NULL
                    $ownership_status, // NULL
                    $land_document, // NULL
                    $land_under_school, // NULL
                    $land_not_under_school, // NULL
                    $not_under_kanal, // NULL
                    $not_under_marla, // NULL
                    $reason_not_under_control, // NULL
                    $encroachment_details, // NULL
                    $legal_issues, // NULL
                    $legal_issue_type, // NULL
                    $court_case_number, // NULL
                    $court_name, // NULL
                    $legal_issue_details, // NULL
                    $legal_status, // NULL
                    $no_land_reason
                );
            } else {
                // Bind with actual values for land available case
                $stmt->bind_param(
                    "ssiissssiiisssssssss",
                    $emis_code,
                    $land_available,
                    $kanal,
                    $marla,
                    $land_type,
                    $ownership_status,
                    $land_document,
                    $land_under_school,
                    $land_not_under_school,
                    $not_under_kanal,
                    $not_under_marla,
                    $reason_not_under_control,
                    $encroachment_details,
                    $legal_issues,
                    $legal_issue_type,
                    $court_case_number,
                    $court_name,
                    $legal_issue_details,
                    $legal_status,
                    $no_land_reason
                );
            }
            
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "School land information saved successfully!";
                header("Location: school_step3.php");
                exit();
            } else {
                throw new Exception("Database execution error: " . $stmt->error);
            }
        } catch (Exception $e) {
            $error_message = "Error saving data: " . $e->getMessage();
        }
    } else {
        $error_message = implode("<br>", $errors);
        
        // Store form data in session to repopulate the form
        $_SESSION['form_data'] = $form_data;
        $_SESSION['error_message'] = $error_message;
        header("Location: school_step2.php");
        exit();
    }
} else {
    // If not POST request, redirect to form
    header("Location: school_step2.php");
    exit();
}
?>