<?php
require_once 'config.php';

// Start session for error/success messages
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST;
    
    // Validate SchoolID
    if (!isset($data['SchoolID']) || empty($data['SchoolID'])) {
        header('Location: schooldesc.php?error=1&msg=' . urlencode('معرف المدرسة غير موجود'));
        exit();
    }
    
    // Auto-calculate totals if needed
    if (isset($data['total_male_students']) && isset($data['total_female_students'])) {
        $data['total_students'] = intval($data['total_male_students']) + intval($data['total_female_students']);
    }
    
    if (isset($data['female_teachers']) && isset($data['male_teachers'])) {
        $data['total_teachers'] = intval($data['female_teachers']) + intval($data['male_teachers']);
    }
    
    // Validate required fields
    $required = ['school_type', 'study_period', 'environment'];
    foreach ($required as $field) {
        if (empty($data[$field])) {
            header('Location: schooldesc.php?error=1&msg=' . urlencode('جميع الحقول المطلوبة يجب تعبئتها') . '&school_id=' . $data['SchoolID']);
            exit();
        }
    }
    
    // Save school data
    if (saveSchoolData($conn, $data)) {
        $schoolId = intval($data['SchoolID']);
        $schoolName = getSchoolName($conn, $schoolId);
        
        // Redirect to schooldesc.php with success
        header('Location: schooldesc.php?success=1&school_id=' . $schoolId . '&school_name=' . urlencode($schoolName));
        exit();
    } else {
        // If save failed, redirect back to schooldesc.php with error
        header('Location: schooldesc.php?error=1&msg=' . urlencode('حدث خطأ أثناء حفظ البيانات') . '&school_id=' . $data['SchoolID']);
        exit();
    }
} else {
    header('Location: index.php');
    exit();
}
?>