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

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

header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Verify this is an admin user
if ($_SESSION["role"] !== ROLE_ADMIN) {
    echo json_encode(['success' => false, 'message' => 'Only admins can trigger suspension']);
    exit;
}

$school_id = $_SESSION["school_id"];

// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Verify the action
if (!isset($_POST['action']) || $_POST['action'] !== 'suspend') {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

try {
    // Check if subscription has actually expired
    $sql_check = "SELECT subscription_expiry_date FROM schools WHERE school_id = ?";
    if ($stmt_check = $conn->prepare($sql_check)) {
        $stmt_check->bind_param("i", $school_id);
        $stmt_check->execute();
        $stmt_check->bind_result($expiry_date);
        $stmt_check->fetch();
        $stmt_check->close();

        if (empty($expiry_date)) {
            echo json_encode(['success' => false, 'message' => 'No expiry date set']);
            exit;
        }

        // Check if subscription has expired
        $expiry_timestamp = strtotime($expiry_date . ' 23:59:59');
        $current_timestamp = time();

        if ($current_timestamp < $expiry_timestamp) {
            echo json_encode(['success' => false, 'message' => 'Subscription has not expired yet']);
            exit;
        }
    }

    // Update school status to 'suspended'
    $sql_suspend = "UPDATE schools SET status = 'suspended' WHERE school_id = ?";
    if ($stmt_suspend = $conn->prepare($sql_suspend)) {
        $stmt_suspend->bind_param("i", $school_id);
        
        if ($stmt_suspend->execute()) {
            // Also update all users in this school to suspended status
            $sql_users = "UPDATE users SET status = 'suspended' WHERE school_id = ?";
            if ($stmt_users = $conn->prepare($sql_users)) {
                $stmt_users->bind_param("i", $school_id);
                $stmt_users->execute();
                $stmt_users->close();
            }

            // Log the suspension
            error_log("School ID $school_id automatically suspended due to subscription expiry on " . date('Y-m-d H:i:s'));

            echo json_encode([
                'success' => true, 
                'message' => 'School suspended successfully',
                'suspended_at' => date('Y-m-d H:i:s')
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to suspend school: ' . $stmt_suspend->error]);
        }
        $stmt_suspend->close();
    } else {
        echo json_encode(['success' => false, 'message' => 'Database preparation error']);
    }

} catch (Exception $e) {
    error_log("Suspension error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Server error occurred']);
}

$conn->close();
?>