<?php

require_once __DIR__ . '/../library/auth.php';
require_once __DIR__ . '/../library/audit_log.php';

$school_id = $_SESSION['school_id'];
allow_roles(['admin']);


// ======================================================
// FORM SUBMIT CHECK
// ======================================================

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    header("Location: addprofile.php");
    exit;
}


// ======================================================
// FETCH FORM DATA
// ======================================================

$school_name      = trim($_POST['school_name'] ?? '');
$school_address   = trim($_POST['address'] ?? '');
$school_phone     = trim(preg_replace('/[^0-9+ ]/', '', $_POST['phone'] ?? ''));
$school_email     = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
$school_website   = trim($_POST['website'] ?? '');
$school_reg_no    = trim($_POST['reg_no'] ?? '');
$dise_code        = trim($_POST['dise_code'] ?? '');
$current_session  = trim($_POST['session'] ?? '');
$language         = in_array($_POST['language'] ?? 'en', ['en', 'hi', 'ur']) ? $_POST['language'] : 'en';
$currency         = in_array($_POST['currency'] ?? 'INR', ['INR', 'USD']) ? $_POST['currency'] : 'INR';
$result_pattern   = trim($_POST['result_pattern'] ?? '');


// ======================================================
// VALIDATION
// ======================================================

if (empty($school_name)) {

    header("Location: addprofile.php?msg=❌ School Name is required!");
    exit;
}

if (!filter_var($school_email, FILTER_VALIDATE_EMAIL)) {

    header("Location: addprofile.php?msg=❌ Invalid Email Address!");
    exit;
}

if (strlen($school_phone) < 10) {

    header("Location: addprofile.php?msg=❌ Invalid Phone Number!");
    exit;
}


// ======================================================
// LOGO UPLOAD
// ======================================================

$logo_name = $_POST['existing_logo'] ?? '';

if (
    isset($_FILES['school_logo']) &&
    $_FILES['school_logo']['error'] == 0
) {

    $allowed_extensions = ['jpg', 'jpeg', 'png', 'webp'];

    $file_name = $_FILES['school_logo']['name'];
    $tmp_name  = $_FILES['school_logo']['tmp_name'];
    $file_size = $_FILES['school_logo']['size'];

    // VALIDATE FILE SIZE (5MB MAX)
    if ($file_size > 5 * 1024 * 1024) {

        header("Location: addprofile.php?msg=❌ Logo size should not exceed 5MB!");
        exit;
    }

    $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    // VALIDATE EXTENSION
    if (!in_array($extension, $allowed_extensions)) {

        header("Location: addprofile.php?msg=❌ Invalid logo format!");
        exit;
    }

    // VALIDATE MIME TYPE
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $tmp_name);
    finfo_close($finfo);

    $allowed_mimes = ['image/jpeg', 'image/png', 'image/webp'];
    if (!in_array($mime, $allowed_mimes)) {

        header("Location: addprofile.php?msg=❌ Invalid image type!");
        exit;
    }

    // CREATE UPLOAD DIRECTORY
    $upload_dir = "../uploads/school/";

    if (!is_dir($upload_dir)) {

        mkdir($upload_dir, 0755, true);
    }

    // GENERATE UNIQUE FILE NAME
    $logo_name = time() . '_' . bin2hex(random_bytes(8)) . '.' . $extension;

    // MOVE FILE
    if (!move_uploaded_file($tmp_name, $upload_dir . $logo_name)) {

        header("Location: addprofile.php?msg=❌ Logo upload failed!");
        exit;
    }
}


// ======================================================
// CHECK SETTINGS EXIST
// ======================================================

$check = $pdo->prepare("
    SELECT *
    FROM school_settings
    WHERE school_id = ?
");

$check->execute([$school_id]);

$settings = $check->fetch(PDO::FETCH_ASSOC);


// ======================================================
// PREPARE OLD DATA FOR AUDIT
// ======================================================

$old_data = $settings ? [
    'school_name'      => $settings['school_name'] ?? null,
    'school_address'   => $settings['school_address'] ?? null,
    'school_phone'     => $settings['school_phone'] ?? null,
    'school_email'     => $settings['school_email'] ?? null,
    'school_website'   => $settings['school_website'] ?? null,
    'school_reg_no'    => $settings['school_reg_no'] ?? null,
    'dise_code'        => $settings['dise_code'] ?? null,
    'current_session'  => $settings['current_session'] ?? null,
    'language'         => $settings['language'] ?? null,
    'currency'         => $settings['currency'] ?? null,
    'result_pattern'   => $settings['result_pattern'] ?? null,
    'school_logo'      => $settings['school_logo'] ?? null
] : null;


// ======================================================
// UPDATE EXISTING SETTINGS
// ======================================================

if ($exists = $settings) {

    $stmt = $pdo->prepare("

        UPDATE school_settings SET

            school_name      = ?,
            school_address   = ?,
            school_phone     = ?,
            school_email     = ?,
            school_website   = ?,
            school_reg_no    = ?,
            dise_code        = ?,
            current_session  = ?,
            language         = ?,
            currency         = ?,
            result_pattern   = ?,
            school_logo      = ?

        WHERE school_id = ?

    ");

    $stmt->execute([

        $school_name,
        $school_address,
        $school_phone,
        $school_email,
        $school_website,
        $school_reg_no,
        $dise_code,
        $current_session,
        $language,
        $currency,
        $result_pattern,
        $logo_name,
        $school_id

    ]);

} else {

    // ======================================================
    // INSERT NEW SETTINGS
    // ======================================================

    $stmt = $pdo->prepare("

        INSERT INTO school_settings (

            school_id,
            school_name,
            school_address,
            school_phone,
            school_email,
            school_website,
            school_reg_no,
            dise_code,
            current_session,
            language,
            currency,
            result_pattern,
            school_logo

        ) VALUES (

            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?

        )

    ");

    $stmt->execute([

        $school_id,
        $school_name,
        $school_address,
        $school_phone,
        $school_email,
        $school_website,
        $school_reg_no,
        $dise_code,
        $current_session,
        $language,
        $currency,
        $result_pattern,
        $logo_name

    ]);
}


// ======================================================
// AUDIT LOG
// ======================================================

logActivity($pdo, [
    'school_id' => $school_id,
    'user_id'   => $_SESSION['user_id'],
    'module'    => 'School Settings',
    'action'    => $settings ? 'UPDATE' : 'CREATE',
    'record_id' => $school_id,
    'message'   => "School profile " . ($settings ? "updated" : "created") . ": {$school_name}",
    'old_data'  => $old_data,
    'new_data'  => [
        'school_name'      => $school_name,
        'school_address'   => $school_address,
        'school_phone'     => $school_phone,
        'school_email'     => $school_email,
        'school_website'   => $school_website,
        'school_reg_no'    => $school_reg_no,
        'dise_code'        => $dise_code,
        'current_session'  => $current_session,
        'language'         => $language,
        'currency'         => $currency,
        'result_pattern'   => $result_pattern,
        'school_logo'      => $logo_name
    ]
]);


// ======================================================
// REDIRECT
// ======================================================

header("Location: index.php?msg=✅ School Profile " . ($settings ? "Updated" : "Created") . " Successfully!");
exit;

?>