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

// Check connection
if ($conn === false) {
    die("ERROR: Could not connect. " . $conn->connect_error);
}

// Set charset
$conn->set_charset("utf8");

// Check for Super Admin role
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== ROLE_SUPER_ADMIN) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Set content type to JSON
header('Content-Type: application/json');

// Handle different actions
$action = $_GET['action'] ?? '';
$school_id = $_GET['school_id'] ?? '';
$clear_expiry = $_GET['clear_expiry'] ?? false;

if (empty($school_id) || empty($action)) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

try {
    switch ($action) {
        case 'suspend':
            // Start transaction for safe suspension
            $conn->begin_transaction();
            try {
                // Suspend all users in the school
                $sql = "UPDATE users SET status = 'suspended' WHERE school_id = ? AND role IN (1, 2, 3)";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("i", $school_id);
                    if ($stmt->execute()) {
                        $users_updated = $stmt->affected_rows;
                    } else {
                        throw new Exception("Failed to suspend users: " . $stmt->error);
                    }
                    $stmt->close();
                } else {
                    throw new Exception("Database prepare error: " . $conn->error);
                }
                
                // Update BOTH subscription_status AND status fields in schools table
                $school_sql = "UPDATE schools SET subscription_status = 'suspended', status = 'suspended' WHERE school_id = ?";
                if ($school_stmt = $conn->prepare($school_sql)) {
                    $school_stmt->bind_param("i", $school_id);
                    if ($school_stmt->execute()) {
                    } else {
                        throw new Exception("Failed to update school status: " . $school_stmt->error);
                    }
                    $school_stmt->close();
                } else {
                    throw new Exception("Database prepare error for school: " . $conn->error);
                }
                
                $conn->commit();
                echo json_encode(['success' => true, 'message' => 'School suspended successfully (users: ' . $users_updated . ')']);
            } catch (Exception $e) {
                $conn->rollback();
                echo json_encode(['success' => false, 'message' => 'Failed to suspend school: ' . $e->getMessage()]);
            }
            break;

        case 'activate':
            // Check if this is an auto-suspended school (has expired subscription)
            $check_expiry_sql = "SELECT subscription_expiry_date FROM schools WHERE school_id = ?";
            $should_clear_expiry = false;
            
            if ($stmt = $conn->prepare($check_expiry_sql)) {
                $stmt->bind_param("i", $school_id);
                $stmt->execute();
                $stmt->bind_result($expiry_date);
                if ($stmt->fetch()) {
                    // If expiry date is in the past or clear_expiry is requested, clear it
                    if (!empty($expiry_date) && (strtotime($expiry_date) < time() || $clear_expiry)) {
                        $should_clear_expiry = true;
                    }
                }
                $stmt->close();
            }

            // Start transaction for safe activation
            $conn->begin_transaction();
            try {
                // Activate all users in the school
                $sql = "UPDATE users SET status = 'active' WHERE school_id = ? AND role IN (1, 2, 3)";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("i", $school_id);
                    if ($stmt->execute()) {
                        $users_updated = $stmt->affected_rows;
                    } else {
                        throw new Exception("Failed to activate users: " . $stmt->error);
                    }
                    $stmt->close();
                } else {
                    throw new Exception("Database prepare error: " . $conn->error);
                }
                
                // Update BOTH subscription_status AND status fields to active
                $school_sql = "UPDATE schools SET subscription_status = 'active', status = 'active' WHERE school_id = ?";
                if ($school_stmt = $conn->prepare($school_sql)) {
                    $school_stmt->bind_param("i", $school_id);
                    if ($school_stmt->execute()) {
                    } else {
                        throw new Exception("Failed to update school status: " . $school_stmt->error);
                    }
                    $school_stmt->close();
                } else {
                    throw new Exception("Database prepare error for school: " . $conn->error);
                }
                
                // Clear subscription expiry date if needed
                if ($should_clear_expiry) {
                    $clear_expiry_sql = "UPDATE schools SET subscription_expiry_date = NULL WHERE school_id = ?";
                    if ($clear_stmt = $conn->prepare($clear_expiry_sql)) {
                        $clear_stmt->bind_param("i", $school_id);
                        if ($clear_stmt->execute()) {
                        } else {
                            throw new Exception("Failed to clear expiry date: " . $clear_stmt->error);
                        }
                        $clear_stmt->close();
                    } else {
                        throw new Exception("Database prepare error for expiry clear: " . $conn->error);
                    }
                }
                
                $conn->commit();
                if ($should_clear_expiry) {
                    echo json_encode(['success' => true, 'message' => 'School activated successfully and subscription expiry cleared (users: ' . $users_updated . ')']);
                } else {
                    echo json_encode(['success' => true, 'message' => 'School activated successfully (users: ' . $users_updated . ')']);
                }
            } catch (Exception $e) {
                $conn->rollback();
                echo json_encode(['success' => false, 'message' => 'Failed to activate school: ' . $e->getMessage()]);
            }
            break;

        case 'delete':
            // Start transaction for safe deletion
            $conn->begin_transaction();
            
            try {
                // Delete all users in the school
                $sql_users = "DELETE FROM users WHERE school_id = ?";
                if ($stmt = $conn->prepare($sql_users)) {
                    $stmt->bind_param("i", $school_id);
                    $stmt->execute();
                    $stmt->close();
                }

                // Delete school data (invoices, payments, etc.)
                // Note: You may need to add more tables to delete from based on your schema
                $sql_school = "DELETE FROM schools WHERE school_id = ?";
                if ($stmt = $conn->prepare($sql_school)) {
                    $stmt->bind_param("i", $school_id);
                    $stmt->execute();
                    $stmt->close();
                }

                $conn->commit();
                echo json_encode(['success' => true, 'message' => 'School deleted successfully']);
            } catch (Exception $e) {
                $conn->rollback();
                echo json_encode(['success' => false, 'message' => 'Failed to delete school: ' . $e->getMessage()]);
            }
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
}

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