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

// Define role constants
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 0);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 1);

// Check if user is super admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== ROLE_SUPER_ADMIN) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

$response = ['success' => false, 'message' => '', 'school' => null];

if (isset($_GET['school_id'])) {
    $school_id = filter_var($_GET['school_id'], FILTER_VALIDATE_INT);
    
    if (!$school_id) {
        $response['message'] = 'Invalid school ID';
        echo json_encode($response);
        exit;
    }
    
    if (!$conn || !($conn instanceof mysqli)) {
        $response['message'] = 'Database connection error';
        echo json_encode($response);
        exit;
    }
    
    try {
        // Fetch school details with user counts
        $sql = "SELECT 
                    s.school_id,
                    s.school_name,
                    s.abbreviation,
                    s.email,
                    s.phone,
                    s.address,
                    s.logo,
                    s.created_at,
                    s.subscription_expiry_date,
                    s.subscription_status,
                    s.status as school_status,
                    (SELECT COUNT(id) FROM users WHERE school_id = s.school_id AND role = 1) as admin_count,
                    (SELECT COUNT(id) FROM users WHERE school_id = s.school_id AND role = 2) as teacher_count,
                    (SELECT COUNT(id) FROM users WHERE school_id = s.school_id AND role = 3) as student_count,
                    (SELECT COUNT(id) FROM users WHERE school_id = s.school_id) as total_users,
                    (SELECT status FROM users WHERE school_id = s.school_id AND role = 1 LIMIT 1) as admin_status,
                    CASE 
                        WHEN (SELECT status FROM users WHERE school_id = s.school_id AND role = 1 LIMIT 1) = 'suspended' 
                             AND (s.subscription_expiry_date IS NOT NULL AND s.subscription_expiry_date < CURDATE())
                        THEN 'auto_suspended'
                        WHEN (SELECT status FROM users WHERE school_id = s.school_id AND role = 1 LIMIT 1) = 'suspended'
                        THEN 'manually_suspended'
                        ELSE 'active'
                    END as suspension_type
                FROM schools s 
                WHERE s.school_id = ?";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            $response['message'] = 'School not found';
            echo json_encode($response);
            exit;
        }
        
        $school = $result->fetch_assoc();
        $stmt->close();
        
        // Format the data for the frontend
        $school_data = [
            'school_id' => $school['school_id'],
            'school_name' => $school['school_name'],
            'abbreviation' => $school['abbreviation'] ?: 'N/A',
            'email' => $school['email'] ?: 'N/A',
            'phone' => $school['phone'] ?: 'N/A',
            'address' => $school['address'] ?: 'N/A',
            'logo' => $school['logo'] ?: 'images/default_school_logo.png',
            'created_at' => date('F j, Y \a\t g:i A', strtotime($school['created_at'])),
            'subscription_expiry_date' => $school['subscription_expiry_date'] ? date('F j, Y', strtotime($school['subscription_expiry_date'])) : 'Not Set',
            'subscription_status' => ucfirst($school['subscription_status']),
            'status' => $school['school_status'],
            'admin_count' => $school['admin_count'],
            'teacher_count' => $school['teacher_count'],
            'student_count' => $school['student_count'],
            'total_users' => $school['total_users'],
            'admin_status' => $school['admin_status'],
            'suspension_type' => $school['suspension_type']
        ];
        
        // Determine display status
        if ($school['suspension_type'] === 'active') {
            $school_data['status_display'] = 'Active';
            $school_data['status_class'] = 'status-active';
        } elseif ($school['suspension_type'] === 'auto_suspended') {
            $school_data['status_display'] = 'Auto-Suspended';
            $school_data['status_class'] = 'status-auto-suspended';
        } else {
            $school_data['status_display'] = 'Suspended';
            $school_data['status_class'] = 'status-suspended';
        }
        
        // Add additional statistics
        $stats_sql = "SELECT 
                        (SELECT COUNT(*) FROM classes WHERE school_id = s.school_id) as class_count,
                        (SELECT COUNT(*) FROM subjects WHERE school_id = s.school_id) as subject_count,
                        (SELECT COUNT(*) FROM exams WHERE school_id = s.school_id) as exam_count,
                        (SELECT COUNT(*) FROM invoices WHERE school_id = s.school_id) as invoice_count
                      FROM schools s WHERE s.school_id = ?";
        
        $stats_stmt = $conn->prepare($stats_sql);
        $stats_stmt->bind_param("i", $school_id);
        $stats_stmt->execute();
        $stats_result = $stats_stmt->get_result();
        $stats = $stats_result->fetch_assoc();
        $stats_stmt->close();
        
        $school_data['class_count'] = $stats['class_count'];
        $school_data['subject_count'] = $stats['subject_count'];
        $school_data['exam_count'] = $stats['exam_count'];
        $school_data['invoice_count'] = $stats['invoice_count'];
        
        $response['success'] = true;
        $response['school'] = $school_data;
        
    } catch (Exception $e) {
        $response['message'] = 'Database error: ' . $e->getMessage();
        error_log('Get school details error: ' . $e->getMessage());
    }
    
} else {
    $response['message'] = 'School ID is required';
}

echo json_encode($response);

// Close connection
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>