<?php
header('Content-Type: application/json');
require_once '../../includes/config.php'; // Ensure path is correct

$response = ['status' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $name    = $_POST['school_name'] ?? '';
        $email   = $_POST['email'] ?? '';
        $phone   = $_POST['phone_number'] ?? '';
        $address = $_POST['school_address'] ?? '';
        $upload_dir = "../../uploads/settings/";

        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

        // Prepare the text update
        $sql = "UPDATE school_settings SET 
                school_name = :name, email = :email, 
                phone_number = :phone, school_address = :address";
        
        $params = [':name'=>$name, ':email'=>$email, ':phone'=>$phone, ':address'=>$address];

        // Handle School Logo
        if (!empty($_FILES['school_logo']['name'])) {
            $logo_name = "logo_" . time() . "_" . $_FILES['school_logo']['name'];
            move_uploaded_file($_FILES['school_logo']['tmp_name'], $upload_dir . $logo_name);
            $sql .= ", school_logo = :logo";
            $params[':logo'] = $logo_name;
        }

        // Handle Signature
        if (!empty($_FILES['principal_signature']['name'])) {
            $sig_name = "sig_" . time() . "_" . $_FILES['principal_signature']['name'];
            move_uploaded_file($_FILES['principal_signature']['tmp_name'], $upload_dir . $sig_name);
            $sql .= ", principal_signature = :sig";
            $params[':sig'] = $sig_name;
        }

        $sql .= " WHERE id = 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        $response = ['status' => true, 'message' => 'Updated Successfully'];
    } catch (Exception $e) {
        $response['message'] = $e->getMessage();
    }
}
echo json_encode($response);?>