<?php
session_start();
require_once 'config.php';

// Check if user is Super Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 0) {
    header("location: login.php");
    exit;
}

$error_message = "";
$success_message = "";

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $school_name = trim($_POST['school_name']);
    $abbreviation = trim($_POST['abbreviation']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $box_number = trim($_POST['box_number']);
    $motto = trim($_POST['motto']);
    $website = trim($_POST['website']);
    $admin_username = trim($_POST['admin_username']);
    $admin_email = trim($_POST['admin_email']);
    $admin_password = trim($_POST['admin_password']);
    $admin_phone = trim($_POST['admin_phone']);

    // Handle logo upload
    $logo_path = null;
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
        $upload_dir = 'uploads/logos/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        $file_extension = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $logo_filename = 'logo_' . uniqid() . '.' . $file_extension;
        $logo_path = $upload_dir . $logo_filename;
        move_uploaded_file($_FILES['logo']['tmp_name'], $logo_path);
    }

    if (isset($conn) && $conn instanceof mysqli) {
        // Begin transaction
        $conn->begin_transaction();
        
        try {
            // Insert school
            $sql = "INSERT INTO schools (school_name, abbreviation, email, phone, address, box_number, motto, website, logo) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            if ($stmt = $conn->prepare($sql)) {
                $stmt->bind_param("sssssssss", $school_name, $abbreviation, $email, $phone, $address, $box_number, $motto, $website, $logo_path);
                $stmt->execute();
                $new_school_id = $conn->insert_id;
                $stmt->close();

                // Create admin user for the school
                $hashed_password = password_hash($admin_password, PASSWORD_DEFAULT);
                $role_admin = 1; // Admin role
                $status_active = 'active';

                $sql_user = "INSERT INTO users (school_id, username, password, email, phone_number, role, status) 
                             VALUES (?, ?, ?, ?, ?, ?, ?)";
                if ($stmt_user = $conn->prepare($sql_user)) {
                    $stmt_user->bind_param("issisis", $new_school_id, $admin_username, $hashed_password, $admin_email, $admin_phone, $role_admin, $status_active);
                    $stmt_user->execute();
                    $stmt_user->close();

                    $conn->commit();
                    $success_message = "School '$school_name' and admin account created successfully!<br><br>"
                        . "<strong>Login Credentials:</strong><br>"
                        . "Username: <strong>$admin_username@$abbreviation</strong><br>"
                        . "Password: [Password you entered]<br><br>"
                        . "<em>Note: Login format is username@school_abbreviation</em>";
                } else {
                    throw new Exception("Error creating admin user: " . $conn->error);
                }
            } else {
                throw new Exception("Error creating school: " . $conn->error);
            }
        } catch (Exception $e) {
            $conn->rollback();
            $error_message = $e->getMessage();
        }
        
        // Don't close connection yet - header needs it
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New School - Super Admin</title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="images/logo.png" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Fixed Header and Sidebar Layout */
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            height: 100vh;
        }

        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        /* Fixed Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            width: 250px;
            overflow-y: auto;
            z-index: 1000;
            transition: transform 0.3s ease;
        }

        .sidebar.collapsed {
            transform: translateX(-250px);
        }

        /* Main Content Area */
        .main-content {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
            transition: margin-left 0.3s ease;
        }

        .sidebar-collapsed .main-content {
            margin-left: 0;
        }

        /* Fixed Header */
        .header {
            position: sticky;
            top: 0;
            z-index: 999;
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        /* Scrollable Dashboard Content */
        .dashboard-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
            background: #f5f5f5;
        }

        /* Scrollbar Styling */
        .dashboard-content::-webkit-scrollbar {
            width: 8px;
        }

        .dashboard-content::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .dashboard-content::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        .dashboard-content::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        .sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: transparent;
        }

        .sidebar::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 3px;
        }

        .sidebar::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }

        .form-container {
            max-width: 800px;
            margin: 40px auto;
            background: white;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        }

        .form-container h2 {
            color: #4f46e5;
            margin-bottom: 30px;
            text-align: center;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-section h3 {
            color: #333;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #4f46e5;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        .form-group label {
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        .form-group label .required {
            color: #ef4444;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.2s;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #4f46e5;
        }

        .btn-submit {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            color: white;
            padding: 14px 40px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            width: 100%;
            margin-top: 20px;
            transition: transform 0.2s;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
        }

        .btn-back {
            background: #64748b;
            color: white;
            padding: 10px 30px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            margin-bottom: 20px;
        }

        .alert {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .alert-success {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #10b981;
        }

        .alert-error {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #ef4444;
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            .main-content {
                margin-left: 0;
            }
            .dashboard-content {
                padding-bottom: 90px;
            }
            .sidebar {
                transform: translateX(-250px);
            }
            .sidebar.show {
                transform: translateX(0);
            }
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <?php include 'includes/super_admin_sidebar.php'; ?>
        
        <div class="main-content">
            <?php include 'includes/super_admin_header.php'; ?>
            
            <div class="dashboard-content">
                <div class="form-container">
        <a href="super_admin_dashboard.php" class="btn-back"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
        
        <h2><i class="fas fa-school"></i> Add New School</h2>

        <?php if ($error_message): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i> <?php echo $error_message; ?>
            </div>
        <?php endif; ?>

        <?php if ($success_message): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
            </div>
        <?php endif; ?>

        <form method="POST" action="" enctype="multipart/form-data">
            <div class="form-section">
                <h3>School Information</h3>
                <div class="form-row">
                    <div class="form-group">
                        <label>School Name <span class="required">*</span></label>
                        <input type="text" name="school_name" required placeholder="e.g., St. Mary's College">
                    </div>
                    <div class="form-group">
                        <label>Abbreviation <span class="required">*</span></label>
                        <input type="text" name="abbreviation" required placeholder="e.g., SMC">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Email <span class="required">*</span></label>
                        <input type="email" name="email" required placeholder="info@school.com">
                    </div>
                    <div class="form-group">
                        <label>Phone <span class="required">*</span></label>
                        <input type="tel" name="phone" required placeholder="0700000000">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Address</label>
                        <input type="text" name="address" placeholder="School location">
                    </div>
                    <div class="form-group">
                        <label>P.O. Box Number</label>
                        <input type="text" name="box_number" placeholder="P.O. Box 123">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Motto</label>
                        <input type="text" name="motto" placeholder="School motto">
                    </div>
                    <div class="form-group">
                        <label>Website</label>
                        <input type="url" name="website" placeholder="https://school.com">
                    </div>
                </div>

                <div class="form-group full-width">
                    <label>School Logo</label>
                    <input type="file" name="logo" accept="image/*">
                </div>
            </div>

            <div class="form-section">
                <h3>Admin Account Information</h3>
                <p style="background: #fef3c7; padding: 12px; border-radius: 6px; margin-bottom: 15px; color: #92400e;">
                    <i class="fas fa-info-circle"></i> <strong>Note:</strong> The admin will login using the format: <strong>username@school_abbreviation</strong>
                </p>
                <div class="form-row">
                    <div class="form-group">
                        <label>Admin Username <span class="required">*</span></label>
                        <input type="text" name="admin_username" required placeholder="admin">
                    </div>
                    <div class="form-group">
                        <label>Admin Email <span class="required">*</span></label>
                        <input type="email" name="admin_email" required placeholder="admin@school.com">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Admin Password <span class="required">*</span></label>
                        <input type="password" name="admin_password" required placeholder="Strong password">
                    </div>
                    <div class="form-group">
                        <label>Admin Phone</label>
                        <input type="tel" name="admin_phone" placeholder="0700000000">
                    </div>
                </div>
            </div>

            <button type="submit" class="btn-submit">
                <i class="fas fa-plus-circle"></i> Create School & Admin Account
            </button>
        </form>
    </div>
            </div>
        </div>
        
        <?php include 'includes/super_admin_mobile_nav.php'; ?>
    </div>
    
    <script>
        // Sidebar toggle
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        
        if (menuToggle) {
            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('collapsed');
                dashboardContainer.classList.toggle('sidebar-collapsed');
            });
        }
    </script>
</body>
</html>
<?php
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>