<?php
if (isset($_POST['admin_upload_btn'])) {
    function sanitize_input($conn, $input, $transform = null)
    {
        $input = trim($input);
        if ($transform === 'upper') $input = strtoupper($input);
		if ($transform === 'ucwords') $input = ucwords($input);
		if ($transform === 'lower') $input = strtolower($input);
        return mysqli_real_escape_string($conn, $input);
    }

    function handle_file_upload($field_name, $primary_dir = 'uploads/school/', $secondary_dir = '../../uploads/school/', $default = 'uploads/school/none.jpg')
    {
        if (!isset($_FILES[$field_name]) || empty($_FILES[$field_name]['name'])) return null;

        $file = $_FILES[$field_name];
        $filename = time() . '_' . basename($file['name']);

        $primary_path = $primary_dir . $filename;
        $secondary_path = $secondary_dir . $filename;

        // Ensure directories exist
        if (!is_dir($primary_dir)) mkdir($primary_dir, 0755, true);
        if (!is_dir($secondary_dir)) mkdir($secondary_dir, 0755, true);

        // Move to primary directory
        if (move_uploaded_file($file['tmp_name'], $primary_path)) {
            copy($primary_path, $secondary_path);
            return $primary_path;
        }

        return null;
    }

    $school_name       = sanitize_input($connection, $_POST['school_name'], 'upper');
    $school_address    = sanitize_input($connection, $_POST['school_address'], 'ucwords');
    $school_motto      = sanitize_input($connection, $_POST['school_motto'], 'ucwords');
    $school_phone      = sanitize_input($connection, $_POST['school_phone'], 'ucwords');
	$school_mail       = sanitize_input($connection, $_POST['school_mail'], 'lower');
	$school_website    = sanitize_input($connection, $_POST['school_website'], 'lower');
    $school_whatsapp   = sanitize_input($connection, $_POST['school_whatsapp'], 'ucwords');
    $school_short_name = sanitize_input($connection, $_POST['school_short_name'], 'ucwords');
    $adm_no_initials   = sanitize_input($connection, $_POST['adm_no_initials'], 'ucwords');
    $date              = date('Y-m-d');

    // Fetch existing file paths if they exist
    $existing_data = [];
    $query_check = "SELECT * FROM `administratives`";
    $result = mysqli_query($connection, $query_check);
    if ($result && mysqli_num_rows($result) > 0) {
        $existing_data = mysqli_fetch_assoc($result);
    }

    // Handle uploads (null if not uploaded)
    $school_logo_upload    = handle_file_upload('logo');
    $school_stamp_upload   = handle_file_upload('stamp');
    $school_favicon_upload = handle_file_upload('favicon');

    // Determine actual file to use (existing or uploaded or default if first time)
    $school_logo = $school_logo_upload ?? ($existing_data['school_logo'] ?? 'uploads/school/none.jpg');
    $school_stamp = $school_stamp_upload ?? ($existing_data['school_stamp'] ?? 'uploads/school/none.jpg');
    $school_favicon = $school_favicon_upload ?? ($existing_data['school_favicon'] ?? 'uploads/school/none.jpg');

    // First-time validation
    if (empty($existing_data)) {
        if ($school_logo === 'uploads/school/none.jpg' || $school_stamp === 'uploads/school/none.jpg' || $school_favicon === 'uploads/school/none.jpg') {
            $_SESSION['msg'] = "Logo, Stamp, and Favicon are required for first-time setup.";
            $_SESSION['type'] = "error";
            header("Location: manage_school_info");
            exit();
        }
    }

    // Save or update data
    if (!empty($existing_data)) {
        $query = "UPDATE `administratives` SET
                    `school_name` = '{$school_name}',
                    `school_address` = '{$school_address}',
                    `school_motto` = '{$school_motto}',
                    `school_phone` = '{$school_phone}',
                    `school_mail` = '{$school_mail}',
                    `school_website` = '{$school_website}',
                    `school_whatsapp` = '{$school_whatsapp}',
                    `adm_no_initials` = '{$adm_no_initials}',
                    `school_short_name` = '{$school_short_name}',
                    `school_logo` = '{$school_logo}',
                    `school_stamp` = '{$school_stamp}',
                    `school_favicon` = '{$school_favicon}',
                    `upload_date` = '{$date}'";
    } else {
        $query = "INSERT INTO `administratives` (
                    `school_name`, `school_address`, `school_motto`, `school_phone`, `school_mail`, `school_website`, `school_whatsapp`, `adm_no_initials`,
                    `school_short_name`, `school_logo`, `school_stamp`, `school_favicon`, `upload_date`
                ) VALUES (
                    '{$school_name}', '{$school_address}', '{$school_motto}', '{$school_phone}', '{$school_mail}', '{$school_website}', '{$school_whatsapp}', '{$adm_no_initials}',
                    '{$school_short_name}', '{$school_logo}', '{$school_stamp}', '{$school_favicon}', '{$date}'
                )";
    }

    $run_query = mysqli_query($connection, $query);
    if ($run_query) {
        $_SESSION['msg'] = "School Information saved successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Failed to save School information.";
        $_SESSION['type'] = "error";
    }

    header("Location: manage_school_info");
    exit();
}
?>

<?php
// Fetch existing data from `administratives`
$admin_data = [
    'school_name' => '',
    'school_address' => '',
    'school_motto' => '',
    'adm_no_initials' => '',
    'school_phone' => '',
    'school_mail' => '',
    'school_website' => '',
    'school_whatsapp' => '',
    'school_short_name' => '',
    'school_logo' => '',
    'school_stamp' => '',
    'school_favicon' => ''
];

$query = "SELECT * FROM `administratives` LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_num_rows($result) > 0) {
    $admin_data = mysqli_fetch_assoc($result);
}
?>

