<?php 
// school_step1_save.php
// Save handler for School Profile Step 1

// 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';

// Get EMIS code from session or POST
$emis_code = isset($_POST['emis_code']) ? $_POST['emis_code'] : $_SESSION['emis_code'];

// Verify EMIS code exists in registrations
$stmt = $conn->prepare("SELECT * FROM registrations WHERE emis_code = ?");
$stmt->bind_param("s", $emis_code);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    $response = [
        'success' => false,
        'message' => "Invalid EMIS Code. Please try again.",
        'redirect' => "school_step1.php"
    ];
    echo json_encode($response);
    exit();
}

$user = $result->fetch_assoc();
$stmt->close();

// Normalize year function: returns NULL for empty or invalid years, ensures no 0000
function normalizeYear($year) {
    $year = trim($year);
    if (empty($year) || $year === '0000' || !preg_match('/^\d{4}$/', $year)) {
        return null;
    }
    $yearInt = intval($year);
    return ($yearInt >= 1900 && $yearInt <= intval(date('Y'))) ? $yearInt : null;
}

// Initialize response array
$response = [
    'success' => false,
    'message' => '',
    'redirect' => ''
];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Debug: Log all POST data
    error_log("School Step 1 - POST data received for EMIS: " . $emis_code);
    
    // Sanitize all input fields
    $school_name = isset($_POST['school_name']) ? trim($_POST['school_name']) : '';
    $ddo_code = isset($_POST['ddo_code']) ? trim($_POST['ddo_code']) : null;
    $school_branch = isset($_POST['school_branch']) ? trim($_POST['school_branch']) : null;
    $school_bisp = isset($_POST['school_bisp']) ? trim($_POST['school_bisp']) : null;
    
    // Year fields
    $est_year = normalizeYear($_POST['est_year'] ?? '');
    $first_upgrade_year = normalizeYear($_POST['first_upgrade_year'] ?? '');
    $second_upgrade_year = normalizeYear($_POST['second_upgrade_year'] ?? '');
    $third_upgrade_year = normalizeYear($_POST['third_upgrade_year'] ?? '');
    $first_degrade_year = normalizeYear($_POST['first_degrade_year'] ?? '');
    $second_degrade_year = normalizeYear($_POST['second_degrade_year'] ?? '');
    
    // Upgrade/Degrade fields - IMPORTANT: These are now IDs (level_id), not text!
    $established_as = isset($_POST['established_as']) ? intval($_POST['established_as']) : 0;
    $first_upgrade_as = isset($_POST['first_upgrade_as']) && $_POST['first_upgrade_as'] !== '' ? intval($_POST['first_upgrade_as']) : null;
    $second_upgrade_as = isset($_POST['second_upgrade_as']) && $_POST['second_upgrade_as'] !== '' ? intval($_POST['second_upgrade_as']) : null;
    $third_upgrade_as = isset($_POST['third_upgrade_as']) && $_POST['third_upgrade_as'] !== '' ? intval($_POST['third_upgrade_as']) : null;
    $first_degrade_as = isset($_POST['first_degrade_as']) && $_POST['first_degrade_as'] !== '' ? intval($_POST['first_degrade_as']) : null;
    $second_degrade_as = isset($_POST['second_degrade_as']) && $_POST['second_degrade_as'] !== '' ? intval($_POST['second_degrade_as']) : null;
    
    // Location IDs
    $district_id = isset($_POST['district_id']) ? intval($_POST['district_id']) : 0;
    $tehsil_id = isset($_POST['tehsil_id']) ? intval($_POST['tehsil_id']) : 0;
    $constituency_id = isset($_POST['constituency_id']) ? intval($_POST['constituency_id']) : 0;
    $union_council_id = isset($_POST['union_council_id']) ? intval($_POST['union_council_id']) : 0;
    
    // Local information
    $village = isset($_POST['village']) ? trim($_POST['village']) : '';
    $post_office = isset($_POST['post_office']) ? trim($_POST['post_office']) : '';
    $locality = isset($_POST['locality']) ? trim($_POST['locality']) : '';
    $zone = isset($_POST['zone']) ? trim($_POST['zone']) : '';
    $school_loc = isset($_POST['school_loc']) ? trim($_POST['school_loc']) : null;
    $distance_from_road = isset($_POST['distance_from_road']) && $_POST['distance_from_road'] !== '' ? floatval($_POST['distance_from_road']) : null;
    
    // Contact information
    $contact_no = isset($_POST['contact_no']) ? trim($_POST['contact_no']) : '';
    $whatsapp_no = isset($_POST['whatsapp_no']) ? trim($_POST['whatsapp_no']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';

    // Get ID values directly from POST (already IDs from the form)
    // These come from the form as integer IDs
    $school_type = isset($_POST['school_type']) ? intval($_POST['school_type']) : 0;
    $school_level = isset($_POST['school_level']) ? intval($_POST['school_level']) : 0;  // This is level_id
    $school_gender = isset($_POST['school_gender']) ? intval($_POST['school_gender']) : 0;
    $education_mode = isset($_POST['education_mode']) ? intval($_POST['education_mode']) : 0;
    $school_shift = isset($_POST['school_shift']) ? intval($_POST['school_shift']) : 0;
    $school_status = isset($_POST['school_status']) ? intval($_POST['school_status']) : 0;

    // Debug field values
    error_log("Field values - school_type: $school_type, school_level: $school_level, school_gender: $school_gender");
    error_log("Field values - education_mode: $education_mode, school_shift: $school_shift, school_status: $school_status");
    error_log("Field values - established_as: $established_as, first_upgrade_as: " . ($first_upgrade_as ?? 'NULL'));

    // Validation errors array
    $errors = [];

    // Required field validation
    if (empty($school_name)) {
        $errors[] = "School Name is required";
    }
    if ($school_type <= 0) {
        $errors[] = "School Type is required";
    }
    if ($school_level <= 0) {
        $errors[] = "School Level is required";
    }
    if ($school_gender <= 0) {
        $errors[] = "School Gender is required";
    }
    if ($education_mode <= 0) {
        $errors[] = "Education Mode is required";
    }
    if ($school_shift <= 0) {
        $errors[] = "School Shift is required";
    }
    if (empty($emis_code)) {
        $errors[] = "EMIS Code is required";
    }
    if (empty($est_year) || $est_year < 1900 || $est_year > date('Y')) {
        $errors[] = "Valid Establishment Year is required";
    }
    if ($established_as <= 0) {
        $errors[] = "Established As field is required";
    }
    if ($district_id <= 0) {
        $errors[] = "District is required";
    }
    if ($tehsil_id <= 0) {
        $errors[] = "Tehsil is required";
    }
    if ($constituency_id <= 0) {
        $errors[] = "Constituency is required";
    }
    if ($union_council_id <= 0) {
        $errors[] = "Union Council is required";
    }
    if (empty($village)) {
        $errors[] = "Village/Town is required";
    }
    if (empty($post_office)) {
        $errors[] = "Post Office is required";
    }
    if (empty($locality)) {
        $errors[] = "Locality is required";
    }
    if (empty($zone)) {
        $errors[] = "Station Type (Zone) is required";
    }
    if ($school_status <= 0) {
        $errors[] = "School Status is required";
    }
    if (empty($contact_no)) {
        $errors[] = "Contact Number is required";
    } elseif (!preg_match('/^03\d{9}$/', $contact_no)) {
        $errors[] = "Invalid Contact Number format. Must start with 03 and have 11 digits";
    }
    if (!empty($whatsapp_no) && !preg_match('/^03\d{9}$/', $whatsapp_no)) {
        $errors[] = "Invalid WhatsApp Number format. Must start with 03 and have 11 digits";
    }
    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid Email Address format";
    }

    // DDO Code validation (if provided)
    if (!empty($ddo_code)) {
        if (!preg_match('/^[A-Z]{2}\d{4}$/', $ddo_code)) {
            $errors[] = "DDO Code must be exactly 2 letters followed by 4 digits (e.g., KJ0123)";
        }
    }

    // Additional validations for upgrade/degrade fields
    if ($first_upgrade_year && !$first_upgrade_as) {
        $errors[] = "If 1st Time Upgradation Year is provided, 1st Time Upgradation As is required";
    }
    if ($second_upgrade_year && !$second_upgrade_as) {
        $errors[] = "If 2nd Time Upgradation Year is provided, 2nd Time Upgradation As is required";
    }
    if ($third_upgrade_year && !$third_upgrade_as) {
        $errors[] = "If 3rd Time Upgradation Year is provided, 3rd Time Upgradation As is required";
    }
    if ($first_degrade_year && !$first_degrade_as) {
        $errors[] = "If 1st Time Degradation Year is provided, 1st Time Degradation As is required";
    }
    if ($second_degrade_year && !$second_degrade_as) {
        $errors[] = "If 2nd Time Degradation Year is provided, 2nd Time Degradation As is required";
    }

    // Check if record already exists for this EMIS code
    $check_stmt = $conn->prepare("SELECT id FROM school_profile WHERE emis_code = ?");
    $check_stmt->bind_param("s", $emis_code);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    $record_exists = ($check_result->num_rows > 0);
    $check_stmt->close();

    // Debug validation errors
    if (count($errors) > 0) {
        error_log("Validation errors for EMIS $emis_code: " . implode(", ", $errors));
    }

    // If there are validation errors, return JSON response
    if (count($errors) > 0) {
        $response['message'] = implode("<br>", $errors);
        $response['redirect'] = "school_step1.php";
        echo json_encode($response);
        exit();
    }

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

    try {
        // Prepare the SQL statement based on whether record exists or not
        if ($record_exists) {
            // UPDATE existing record
            $sql = "UPDATE school_profile SET 
                    school_name = ?, school_type = ?, school_level = ?, school_gender = ?,
                    education_mode = ?, school_shift = ?, ddo_code = ?, school_branch = ?,
                    school_bisp = ?, est_year = ?, established_as = ?, first_upgrade_year = ?,
                    first_upgrade_as = ?, second_upgrade_year = ?, second_upgrade_as = ?,
                    third_upgrade_year = ?, third_upgrade_as = ?, first_degrade_year = ?,
                    first_degrade_as = ?, second_degrade_year = ?, second_degrade_as = ?,
                    district_id = ?, tehsil_id = ?, constituency_id = ?, union_council_id = ?,
                    village = ?, post_office = ?, locality = ?, zone = ?, school_loc = ?,
                    distance_from_road = ?, school_status = ?, contact_no = ?, whatsapp_no = ?,
                    email = ?, updated_at = NOW(), status = 1
                    WHERE emis_code = ?";
            
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            
            // Actually, let's use a simpler approach - bind each parameter individually
            $stmt->bind_param(
                "siiiiissssiisissssssiiiissssssdsssss",
                $school_name, // s
                $school_type, // i
                $school_level, // i
                $school_gender, // i
                $education_mode, // i
                $school_shift, // i
                $ddo_code, // s
                $school_branch, // s
                $school_bisp, // s
                $est_year, // i
                $established_as, // i
                $first_upgrade_year, // i
                $first_upgrade_as, // i

                $second_upgrade_year, // i
                $second_upgrade_as, // i
                $third_upgrade_year, // i
                $third_upgrade_as, // i
                $first_degrade_year, // i
                $first_degrade_as, // i
                $second_degrade_year, // i
                $second_degrade_as, // i
                $district_id, // i
                $tehsil_id, // i
                $constituency_id, // i
                $union_council_id, // i
                $village, // s
                $post_office, // s
                $locality, // s
                $zone, // s
                $school_loc, // s
                $distance_from_road, // d
                $school_status, // s
                $contact_no, // s
                $whatsapp_no, // s
                $email, // s
                $emis_code // s
            );
        } else {
            // INSERT new record
            $sql = "INSERT INTO school_profile (
                emis_code, school_name, school_type, school_level, school_gender,
                education_mode, school_shift, ddo_code, school_branch, school_bisp,
                est_year, established_as, first_upgrade_year, first_upgrade_as,
                second_upgrade_year, second_upgrade_as, third_upgrade_year, third_upgrade_as,
                first_degrade_year, first_degrade_as, second_degrade_year, second_degrade_as,
                district_id, tehsil_id, constituency_id, union_council_id,
                village, post_office, locality, zone, school_loc,
                distance_from_road, school_status, contact_no, whatsapp_no,
                email, status
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1
            )";
            
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            // Bind parameters for INSERT
            $stmt->bind_param(
                "ssiiiiissssiisissssssiiiissssssdssss",
                $emis_code, // s
                $school_name, // s
                $school_type, // i
                $school_level, // i
                $school_gender, // i
                $education_mode, // i
                $school_shift, // i
                $ddo_code, // s
                $school_branch, // s
                $school_bisp, // s
                $est_year, // i
                $established_as, // i
                $first_upgrade_year, // i
                $first_upgrade_as, // i
                $second_upgrade_year, // i
                $second_upgrade_as, // i
                $third_upgrade_year, // i
                $third_upgrade_as, // i
                $first_degrade_year, // i
                $first_degrade_as, // i
                $second_degrade_year, // i
                $second_degrade_as, // i
                $district_id, // i
                $tehsil_id, // i
                $constituency_id, // i
                $union_council_id, // i
                $village, // s
                $post_office, // s
                $locality, // s
                $zone, // s
                $school_loc, // s
                $distance_from_road, // d
                $school_status, // s
                $contact_no, // s
                $whatsapp_no, // s
                $email // s
            );
        }

        // Execute the statement
        if ($stmt->execute()) {
			$_SESSION['success_message'] = "School profile information saved successfully!";
            //header("Location: school_step2.php");
            //exit();
            $affected_rows = $stmt->affected_rows;
            $stmt->close();
            
            // Commit transaction
            $conn->commit();
            
            // Success message
            error_log("School Profile Step 1 saved successfully for EMIS: $emis_code. Affected rows: $affected_rows");
            
            // Check completion status
            require_once 'school_profile_completion_check.php';
            $completion = checkSchoolProfileCompletion($conn, $emis_code);
            
            // Determine next step: after step 1, go to step 2
            $next_step = 2;
            
            // If profile is complete, redirect to dashboard
            if ($completion['percentage'] == 100) {
                $response['success'] = true;
                $response['message'] = "Congratulations! Your school profile is complete.";
                $response['redirect'] = "school_dashboard.php";
            } else {
                // Redirect to next step
                $response['success'] = true;
                $response['message'] = "Step 1 completed successfully!";
				$response['redirect'] = "school_step" . $next_step . ".php?emis_code=" . urlencode($emis_code);
            }
            
            echo json_encode($response);
            exit();
        } else {
            throw new Exception("Database error: " . $stmt->error);
        }
        
    } catch (Exception $e) {
        // Rollback transaction on error
        if ($conn) {
            $conn->rollback();
        }
        
        error_log("Error saving school profile for EMIS $emis_code: " . $e->getMessage());
        error_log("SQL Error: " . ($stmt->error ?? 'No statement error'));
        
        $response['message'] = "Error saving data: " . $e->getMessage();
        $response['redirect'] = "school_step1.php";
        echo json_encode($response);
        exit();
    }
} else {
    // Invalid request method
    $response['success'] = false;
    $response['message'] = "Invalid request method";
    $response['redirect'] = "school_step1.php";
    echo json_encode($response);
    exit();
}
?>