<?php

session_start();

require_once __DIR__ . '/../../library/config.php';
require_once __DIR__ . '/../../library/super_admin_auth.php';
require_once __DIR__ . '/../../library/super_admin_audit_log.php';

$page_title = 'Edit School';

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';

$error = '';
$success = '';

/*
|--------------------------------------------------------------------------
| VALIDATE SCHOOL ID
|--------------------------------------------------------------------------
*/

$school_id = isset($_GET['id'])
    ? (int) $_GET['id']
    : 0;

if ($school_id <= 0) {

    die('Invalid school ID.');
}

/*
|--------------------------------------------------------------------------
| FETCH SCHOOL
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT *
    FROM schools
    WHERE id = ?
    LIMIT 1
");

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

$school = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$school) {

    die('School not found.');
}

/*
|--------------------------------------------------------------------------
| FETCH SETTINGS
|--------------------------------------------------------------------------
*/

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

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

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

/*
|--------------------------------------------------------------------------
| GET SUPER ADMIN DATA
|--------------------------------------------------------------------------
*/

$super_admin_id = $_SESSION['super_admin_id'] ?? null;
$super_admin_name = $_SESSION['super_admin_name'] ?? 'Unknown';
$super_admin_email = $_SESSION['super_admin_email'] ?? 'Unknown';

/*
|--------------------------------------------------------------------------
| FORM SUBMIT
|--------------------------------------------------------------------------
*/

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

    /*
    |--------------------------------------------------------------------------
    | CSRF CHECK
    |--------------------------------------------------------------------------
    */

    if (
        !isset($_POST['csrf_token']) ||
        !hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'])
    ) {

        die('Invalid CSRF token.');
    }

    /*
    |--------------------------------------------------------------------------
    | GET FORM DATA
    |--------------------------------------------------------------------------
    */

    $school_name = trim($_POST['school_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $website = trim($_POST['website'] ?? '');
    $dise_code = trim($_POST['dise_code'] ?? '');
    $session_year = trim($_POST['session_year'] ?? '');
    $status = trim($_POST['status'] ?? 'active');
    $subscription_status = trim($_POST['subscription_status'] ?? 'Active');
    $subscription_start = trim($_POST['subscription_start'] ?? '');
    $subscription_end = trim($_POST['subscription_end'] ?? '');

    /*
    |--------------------------------------------------------------------------
    | VALIDATION
    |--------------------------------------------------------------------------
    */

    if (empty($school_name)) {

        $error = 'School name is required.';

    } else {

        try {

            $pdo->beginTransaction();

            /*
            |--------------------------------------------------------------------------
            | STORE OLD DATA FOR AUDIT
            |--------------------------------------------------------------------------
            */

            $old_school_data = [
                'name'                 => $school['name'],
                'phone'                => $school['phone'] ?? null,
                'email'                => $school['email'] ?? null,
                'status'               => $school['status'],
                'subscription_status'  => $school['subscription_status'] ?? null,
                'subscription_start'   => $school['subscription_start'] ?? null,
                'subscription_end'     => $school['subscription_end'] ?? null
            ];

            $old_settings_data = [
                'school_name'    => $settings['school_name'] ?? null,
                'school_phone'   => $settings['school_phone'] ?? null,
                'school_email'   => $settings['school_email'] ?? null,
                'school_address' => $settings['school_address'] ?? null,
                'school_website' => $settings['school_website'] ?? null,
                'dise_code'      => $settings['dise_code'] ?? null,
                'current_session' => $settings['current_session'] ?? null
            ];

            /*
            |--------------------------------------------------------------------------
            | UPDATE SCHOOLS TABLE
            |--------------------------------------------------------------------------
            */

            $updateSchool = $pdo->prepare("
                UPDATE schools
                SET
                    name = ?,
                    phone = ?,
                    email = ?,
                    status = ?,
                    subscription_status = ?,
                    subscription_start = ?,
                    subscription_end = ?
                WHERE id = ?
                LIMIT 1
            ");

            $updateSchool->execute([
                $school_name,
                $phone,
                $email,
                $status,
                $subscription_status,
                $subscription_start,
                $subscription_end,
                $school_id
            ]);

            /*
            |--------------------------------------------------------------------------
            | UPDATE SETTINGS TABLE
            |--------------------------------------------------------------------------
            */

            $updateSettings = $pdo->prepare("
                UPDATE school_settings
                SET
                    school_name = ?,
                    school_phone = ?,
                    school_email = ?,
                    school_address = ?,
                    school_website = ?,
                    dise_code = ?,
                    current_session = ?
                WHERE school_id = ?
                LIMIT 1
            ");

            $updateSettings->execute([
                $school_name,
                $phone,
                $email,
                $address,
                $website,
                $dise_code,
                $session_year,
                $school_id
            ]);

            $pdo->commit();

            /*
            |--------------------------------------------------------------------------
            | NEW DATA FOR AUDIT
            |--------------------------------------------------------------------------
            */

            $new_school_data = [
                'name'                 => $school_name,
                'phone'                => $phone,
                'email'                => $email,
                'status'               => $status,
                'subscription_status'  => $subscription_status,
                'subscription_start'   => $subscription_start,
                'subscription_end'     => $subscription_end
            ];

            $new_settings_data = [
                'school_name'     => $school_name,
                'school_phone'    => $phone,
                'school_email'    => $email,
                'school_address'  => $address,
                'school_website'  => $website,
                'dise_code'       => $dise_code,
                'current_session' => $session_year
            ];

            /*
            |--------------------------------------------------------------------------
            | GBPDETERMINE WHAT CHANGED
            |--------------------------------------------------------------------------
            */

            $changes = [];
            if ($old_school_data['name'] !== $new_school_data['name']) {
                $changes[] = "School name: {$old_school_data['name']} → {$new_school_data['name']}";
            }
            if ($old_school_data['status'] !== $new_school_data['status']) {
                $changes[] = "Status: {$old_school_data['status']} → {$new_school_data['status']}";
            }
            if ($old_school_data['subscription_status'] !== $new_school_data['subscription_status']) {
                $changes[] = "Subscription: {$old_school_data['subscription_status']} → {$new_school_data['subscription_status']}";
            }

            $audit_message = empty($changes) 
                ? "School updated: {$school_name}"
                : "School updated: {$school_name} (" . implode(', ', $changes) . ")";

            /*
            |--------------------------------------------------------------------------
            | AUDIT LOG
            |--------------------------------------------------------------------------
            */

            logSuperAdminActivity($pdo, [
                'super_admin_id'   => $super_admin_id,
                'super_admin_email' => $super_admin_email,
                'super_admin_name'  => $super_admin_name,
                'module'            => 'School Management',
                'action'            => 'UPDATE',
                'record_id'         => $school_id,
                'message'           => $audit_message,
                'old_data'          => [
                    'school'    => $old_school_data,
                    'settings'  => $old_settings_data
                ],
                'new_data'          => [
                    'school'    => $new_school_data,
                    'settings'  => $new_settings_data
                ]
            ]);

            $success = 'School updated successfully.';

            /*
            |--------------------------------------------------------------------------
            | REFRESH DATA
            |--------------------------------------------------------------------------
            */

            $stmt->execute([$school_id]);
            $school = $stmt->fetch(PDO::FETCH_ASSOC);

            $settingsStmt->execute([$school_id]);
            $settings = $settingsStmt->fetch(PDO::FETCH_ASSOC);

        } catch (Exception $e) {

            $pdo->rollBack();

            error_log("School update failed: " . $e->getMessage());

            $error = 'Something went wrong.';
        }
    }
}

/*
|--------------------------------------------------------------------------
| CSRF TOKEN
|--------------------------------------------------------------------------
*/

if (empty($_SESSION['csrf_token'])) {

    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

?>

<!-- Content Header -->

<section class="content-header">

    <div class="container-fluid">

        <div class="row mb-2">

            <div class="col-sm-6">

                <h1>

                    Edit School

                </h1>

            </div>

            <div class="col-sm-6 text-right">

                <a
                    href="index.php"
                    class="btn btn-secondary"
                >

                    Back

                </a>

            </div>

        </div>

    </div>

</section>

<!-- Main Content -->

<section class="content">

    <div class="container-fluid">

        <div class="card card-warning">

            <div class="card-header">

                <h3 class="card-title">

                    School Details

                </h3>

            </div>

            <form method="POST">

                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= htmlspecialchars($_SESSION['csrf_token']); ?>"
                >

                <div class="card-body">

                    <?php if ($error): ?>

                        <div class="alert alert-danger">

                            <?= htmlspecialchars($error); ?>

                        </div>

                    <?php endif; ?>

                    <?php if ($success): ?>

                        <div class="alert alert-success">

                            <?= htmlspecialchars($success); ?>

                        </div>

                    <?php endif; ?>

                    <div class="row">

                        <!-- School Name -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    School Name

                                </label>

                                <input
                                    type="text"
                                    name="school_name"
                                    class="form-control"
                                    required
                                    value="<?= htmlspecialchars($school['name']); ?>"
                                >

                            </div>

                        </div>

                        <!-- Phone -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    Phone

                                </label>

                                <input
                                    type="text"
                                    name="phone"
                                    class="form-control"
                                    value="<?= htmlspecialchars($school['phone'] ?? ''); ?>"
                                >

                            </div>

                        </div>

                        <!-- Email -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    Email

                                </label>

                                <input
                                    type="email"
                                    name="email"
                                    class="form-control"
                                    value="<?= htmlspecialchars($school['email'] ?? ''); ?>"
                                >

                            </div>

                        </div>

                        <!-- Website -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    Website

                                </label>

                                <input
                                    type="text"
                                    name="website"
                                    class="form-control"
                                    value="<?= htmlspecialchars($settings['school_website'] ?? ''); ?>"
                                >

                            </div>

                        </div>

                        <!-- Session -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    Session

                                </label>

                                <input
                                    type="text"
                                    name="session_year"
                                    class="form-control"
                                    value="<?= htmlspecialchars($settings['current_session'] ?? ''); ?>"
                                >

                            </div>

                        </div>

                        <!-- DISE -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    DISE Code

                                </label>

                                <input
                                    type="text"
                                    name="dise_code"
                                    class="form-control"
                                    value="<?= htmlspecialchars($settings['dise_code'] ?? ''); ?>"
                                >

                            </div>

                        </div>

                        <!-- Status -->

                        <div class="col-md-6">

                            <div class="form-group">

                                <label>

                                    Status

                                </label>

                                <select
                                    name="status"
                                    class="form-control"
                                >

                                    <option
                                        value="active"
                                        <?= $school['status'] === 'active' ? 'selected' : ''; ?>
                                    >

                                        Active

                                    </option>

                                    <option
                                        value="inactive"
                                        <?= $school['status'] === 'inactive' ? 'selected' : ''; ?>
                                    >

                                        Inactive

                                    </option>

                                </select>

                            </div>

                        </div>

                        <!-- Address -->

                        <div class="col-md-12">

                            <div class="form-group">

                                <label>

                                    Address

                                </label>

                                <textarea
                                    name="address"
                                    class="form-control"
                                    rows="3"
                                ><?= htmlspecialchars($settings['school_address'] ?? ''); ?></textarea>

                            </div>

                        </div>
						<!-- Subscription Status -->

<div class="col-md-4">

    <div class="form-group">

        <label>

            Subscription Status

        </label>

        <select
            name="subscription_status"
            class="form-control"
        >

            <option
                value="Active"
                <?= ($school['subscription_status'] ?? '') === 'Active' ? 'selected' : ''; ?>
            >
                Active
            </option>

            <option
                value="Trial"
                <?= ($school['subscription_status'] ?? '') === 'Trial' ? 'selected' : ''; ?>
            >
                Trial
            </option>

            <option
                value="Expired"
                <?= ($school['subscription_status'] ?? '') === 'Expired' ? 'selected' : ''; ?>
            >
                Expired
            </option>

        </select>

    </div>

</div>

<!-- Subscription Start -->

<div class="col-md-4">

    <div class="form-group">

        <label>

            Subscription Start

        </label>

        <input
            type="date"
            name="subscription_start"
            class="form-control"
            value="<?= htmlspecialchars($school['subscription_start'] ?? ''); ?>"
        >

    </div>

</div>

<!-- Subscription End -->

<div class="col-md-4">

    <div class="form-group">

        <label>

            Subscription End

        </label>

        <input
            type="date"
            name="subscription_end"
            class="form-control"
            value="<?= htmlspecialchars($school['subscription_end'] ?? ''); ?>"
        >

    </div>

</div>

                    </div>

                </div>

                <div class="card-footer">

                    <button
                        type="submit"
                        class="btn btn-warning"
                    >

                        <i class="fas fa-save"></i>

                        Update School

                    </button>

                </div>

            </form>

        </div>

    </div>

</section>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>