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

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

$response = ['success' => false, 'message' => 'Invalid request'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['school_id'])) {
    $school_id = intval($_POST['school_id']);
    $expiry_date = $_POST['expiry_date'] ?? '';
    $is_clearing = isset($_POST['clear']) && $_POST['clear'] === 'true';
    
    // Check if we're clearing the timer
    if ($is_clearing || empty($expiry_date)) {
        // Clear the expiry date (set to NULL)
        if (isset($conn) && $conn instanceof mysqli) {
            // First, ensure the subscription_expiry_date column exists
            $check_column = "SHOW COLUMNS FROM schools LIKE 'subscription_expiry_date'";
            $result = $conn->query($check_column);
            
            if ($result->num_rows === 0) {
                // Add the column if it doesn't exist
                $alter_table = "ALTER TABLE schools ADD COLUMN subscription_expiry_date DATE NULL";
                if (!$conn->query($alter_table)) {
                    $response = ['success' => false, 'message' => 'Database error: Could not add expiry date column'];
                    echo json_encode($response);
                    exit;
                }
            }
            
            // Clear the school's expiry date by setting it to NULL
            $sql = "UPDATE schools SET subscription_expiry_date = NULL WHERE school_id = ?";
            if ($stmt = $conn->prepare($sql)) {
                $stmt->bind_param("i", $school_id);
                if ($stmt->execute()) {
                    $response = ['success' => true, 'message' => 'Subscription timer cleared successfully'];
                } else {
                    $response = ['success' => false, 'message' => 'Failed to clear timer: ' . $stmt->error];
                }
                $stmt->close();
            } else {
                $response = ['success' => false, 'message' => 'Database prepare error: ' . $conn->error];
            }
            
            $conn->close();
        } else {
            $response = ['success' => false, 'message' => 'Database connection failed'];
        }
    } else {
        // Setting/updating the expiry date
        // Validate date format
        $date_parts = explode('-', $expiry_date);
        if (count($date_parts) !== 3 || !checkdate($date_parts[1], $date_parts[2], $date_parts[0])) {
            $response = ['success' => false, 'message' => 'Invalid date format'];
        } else {
            if (isset($conn) && $conn instanceof mysqli) {
                // First, ensure the subscription_expiry_date column exists
                $check_column = "SHOW COLUMNS FROM schools LIKE 'subscription_expiry_date'";
                $result = $conn->query($check_column);
                
                if ($result->num_rows === 0) {
                    // Add the column if it doesn't exist
                    $alter_table = "ALTER TABLE schools ADD COLUMN subscription_expiry_date DATE NULL";
                    if (!$conn->query($alter_table)) {
                        $response = ['success' => false, 'message' => 'Database error: Could not add expiry date column'];
                        echo json_encode($response);
                        exit;
                    }
                }
                
                // Update the school's expiry date
                $sql = "UPDATE schools SET subscription_expiry_date = ? WHERE school_id = ?";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("si", $expiry_date, $school_id);
                    if ($stmt->execute()) {
                        $response = ['success' => true, 'message' => 'Subscription expiry date updated successfully'];
                    } else {
                        $response = ['success' => false, 'message' => 'Failed to update expiry date: ' . $stmt->error];
                    }
                    $stmt->close();
                } else {
                    $response = ['success' => false, 'message' => 'Database prepare error: ' . $conn->error];
                }
                
                $conn->close();
            } else {
                $response = ['success' => false, 'message' => 'Database connection failed'];
            }
        }
    }
}

header('Content-Type: application/json');
echo json_encode($response);
?>