<?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 = 'Create School';

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

// ======================================================
// DEFAULT VARIABLES
// ======================================================

$error = '';
$success = '';
$school_id_created = null;

// ======================================================
// 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 VALIDATION
    // ==================================================

    if (
        !isset($_POST['csrf_token']) ||
        !hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'])
    ) {
        $error = 'Invalid request.';
    }

    else {
        // ==================================================
        // GET FORM DATA
        // ==================================================

        $school_name = trim($_POST['school_name'] ?? '');
        $admin_name = trim($_POST['admin_name'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $subscription_years = (int) ($_POST['subscription_years'] ?? 1);

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

        if (
            empty($school_name) ||
            empty($admin_name) ||
            empty($username) ||
            empty($password)
        ) {
            $error = 'All fields are required.';
        }

        elseif (strlen($school_name) < 3) {
            $error = 'School name must be at least 3 characters.';
        }

        elseif (strlen($username) < 3) {
            $error = 'Username must be at least 3 characters.';
        }

        elseif (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters.';
        }

        elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
            $error = 'Username can only contain letters, numbers and underscores.';
        }

        else {
            // ==================================================
            // CHECK DUPLICATE USERNAME
            // ==================================================

            $checkStmt = $pdo->prepare("
                SELECT id
                FROM users
                WHERE username = ?
                LIMIT 1
            ");

            $checkStmt->execute([$username]);

            if ($checkStmt->fetch()) {
                $error = 'Username already exists.';
            }

            else {
                try {
                    // ==========================================
                    // START TRANSACTION
                    // ==========================================

                    $pdo->beginTransaction();

                    // ==========================================
                    // CREATE SCHOOL
                    // ==========================================

                    $schoolStmt = $pdo->prepare("
                        INSERT INTO schools
                        (
                            name,
                            status,
                            subscription_status,
                            subscription_start,
                            subscription_end
                        )
                        VALUES
                        (
                            ?,
                            'active',
                            'Active',
                            CURDATE(),
                            DATE_ADD(
                                CURDATE(),
                                INTERVAL ? YEAR
                            )
                        )
                    ");

                    $schoolStmt->execute([
                        $school_name,
                        $subscription_years
                    ]);

                    $school_id_created = $pdo->lastInsertId();

                    // ==========================================
                    // CREATE SCHOOL SETTINGS
                    // ==========================================

                    $current_session = date('Y') . '-' . substr(date('Y') + 1, -2);

                    $settingsStmt = $pdo->prepare("
                        INSERT INTO school_settings
                        (
                            school_id,
                            school_name,
                            current_session
                        )
                        VALUES
                        (
                            ?, ?, ?
                        )
                    ");

                    $settingsStmt->execute([
                        $school_id_created,
                        $school_name,
                        $current_session
                    ]);

                    // ==========================================
                    // CREATE ADMIN USER
                    // ==========================================

                    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

                    $userStmt = $pdo->prepare("
                        INSERT INTO users
                        (
                            school_id,
                            username,
                            name,
                            password,
                            role,
                            status
                        )
                        VALUES
                        (
                            ?,
                            ?,
                            ?,
                            ?,
                            'admin',
                            'active'
                        )
                    ");

                    $userStmt->execute([
                        $school_id_created,
                        $username,
                        $admin_name,
                        $hashedPassword
                    ]);

                    $admin_user_id = $pdo->lastInsertId();

                    // ==========================================
                    // COMMIT
                    // ==========================================

                    $pdo->commit();

                    // ==========================================
                    // AUDIT LOG (AFTER COMMIT)
                    // ==========================================

                    try {
                        logSuperAdminActivity($pdo, [
                            'super_admin_id'   => $super_admin_id,
                            'super_admin_email' => $super_admin_email,
                            'super_admin_name'  => $super_admin_name,
                            'module'            => 'School Management',
                            'action'            => 'CREATE',
                            'record_id'         => $school_id_created,
                            'message'           => "New school created: {$school_name}",
                            'old_data'          => null,
                            'new_data'          => [
                                'school_id'         => $school_id_created,
                                'school_name'       => $school_name,
                                'admin_name'        => $admin_name,
                                'admin_username'    => $username,
                                'admin_user_id'     => $admin_user_id,
                                'subscription_years' => $subscription_years,
                                'subscription_end'  => date('Y-m-d', strtotime("+{$subscription_years} years")),
                                'current_session'   => $current_session,
                                'created_by_super_admin' => $super_admin_email
                            ]
                        ]);
                    } catch (Exception $log_error) {
                        // Audit log fail ho to bhi school create rahega
                        error_log('AUDIT LOG ERROR: ' . $log_error->getMessage());
                    }

                    $success = 'School created successfully!';

                    $_POST = [];

                }

                catch (Exception $e) {
                    $pdo->rollBack();

                    error_log('CREATE SCHOOL ERROR: ' . $e->getMessage());

                    $error = 'Something went wrong. Please try again.';
                }
            }
        }
    }
}

// ======================================================
// GENERATE 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>

                    Create School

                </h1>

            </div>

        </div>

    </div>

</section>

<!-- Main Content -->

<section class="content">

    <div class="container-fluid">

        <div class="card card-primary">

            <div class="card-header">

                <h3 class="card-title">

                    School Registration

                </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; ?>

                    <!-- School Name -->

                    <div class="form-group">

                        <label>

                            School Name

                        </label>

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

                    </div>

                    <!-- Admin Name -->

                    <div class="form-group">

                        <label>

                            Admin Name

                        </label>

                        <input
                            type="text"
                            name="admin_name"
                            class="form-control"
                            required
                            maxlength="100"
                            value="<?= htmlspecialchars($_POST['admin_name'] ?? ''); ?>"
                        >

                    </div>

                    <!-- Username -->

                    <div class="form-group">

                        <label>

                            Username

                        </label>

                        <input
                            type="text"
                            name="username"
                            class="form-control"
                            required
                            maxlength="50"
                            autocomplete="off"
                            value="<?= htmlspecialchars($_POST['username'] ?? ''); ?>"
                        >

                    </div>

                    <!-- Password -->

                    <div class="form-group">

                        <label>

                            Password

                        </label>

                        <input
                            type="password"
                            name="password"
                            class="form-control"
                            required
                            minlength="6"
                        >

                    </div>

                </div>

                <div class="card-footer">

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

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

                        Create School

                    </button>

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

                        Back

                    </a>

                </div>

            </form>

        </div>

    </div>

</section>

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