<?php
session_start();
require_once '../config/config.php';
require_once '../../services/EmailService.php';

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check if the user has sufficient permissions (assuming admin level 9 is super admin)
$admin_level = $_SESSION['admin_level'] ?? 0;
if ($admin_level < 9) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

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

// Get admin data from POST request
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$role = $_POST['role'] ?? 'Administrator';
$admin_level = isset($_POST['admin_level']) ? (int)$_POST['admin_level'] : 5;
$status = $_POST['status'] ?? 'active';
$permissions = isset($_POST['permissions']) ? json_decode($_POST['permissions'], true) : null;

// Validate required fields
if (empty($name) || empty($email) || empty($password)) {
    echo json_encode(['success' => false, 'message' => 'Name, email and password are required']);
    exit();
}

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Invalid email format']);
    exit();
}

// Validate admin level (4-9 range)
if ($admin_level < 4 || $admin_level > 9) {
    echo json_encode(['success' => false, 'message' => 'Admin level must be between 4 and 9']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Begin transaction
    $conn->beginTransaction();
    
    // Check if email already exists
    $stmt = $conn->prepare("SELECT COUNT(*) FROM admins WHERE email = ?");
    $stmt->execute([$email]);
    $emailExists = $stmt->fetchColumn() > 0;
    
    if ($emailExists) {
        $conn->rollBack();
        echo json_encode(['success' => false, 'message' => 'Email already exists']);
        exit();
    }
    
    // Hash the password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    
    // Insert admin into the database
    $stmt = $conn->prepare("
        INSERT INTO admins (
            name, email, password, role, admin_level, status, created_at, updated_at
        ) VALUES (
            ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
        )
    ");
    
    $stmt->execute([
        $name,
        $email,
        $hashed_password,
        $role,
        $admin_level,
        $status
    ]);
    
    $admin_id = $conn->lastInsertId();
    
    // Set permissions
    if ($permissions) {
        // Custom permissions provided
        $stmt = $conn->prepare("
            INSERT INTO admin_permissions (
                admin_id, permission_key, is_granted, created_at, updated_at
            ) VALUES (
                ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
            )
        ");
        
        foreach ($permissions as $key => $value) {
            $stmt->execute([
                $admin_id,
                $key,
                $value ? 1 : 0
            ]);
        }
    } else {
        // Set default permissions
        $default_permissions = [
            'view_dashboard' => true,
            'manage_members' => true,
            'view_reports' => true,
            'manage_events' => $admin_level >= 6,
            'manage_finances' => $admin_level >= 7,
            'manage_settings' => $admin_level >= 8,
            'manage_admins' => $admin_level >= 9
        ];
        
        $stmt = $conn->prepare("
            INSERT INTO admin_permissions (
                admin_id, permission_key, is_granted, created_at, updated_at
            ) VALUES (
                ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
            )
        ");
        
        foreach ($default_permissions as $key => $value) {
            $stmt->execute([
                $admin_id,
                $key,
                $value ? 1 : 0
            ]);
        }
    }
    
    // For email, get actual permissions that were set
    $stmt = $conn->prepare("
        SELECT permission_key, is_granted 
        FROM admin_permissions 
        WHERE admin_id = ?
    ");
    $stmt->execute([$admin_id]);
    $actual_permissions = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $actual_permissions[$row['permission_key']] = (bool)$row['is_granted'];
    }
    
    // Log the action
    $stmt = $conn->prepare("
        INSERT INTO admin_logs (admin_id, action, details, created_at)
        VALUES (?, 'create_admin', ?, CURRENT_TIMESTAMP)
    ");
    $stmt->execute([
        $_SESSION['admin_id'],
        'Created new admin: ' . $name . ' (' . $email . ')'
    ]);
    
    // Send welcome email to the new admin
    try {
        $emailService = new EmailService();
        
        // Get permissions description for email
        $permissions_list = '';
        foreach ($actual_permissions as $key => $value) {
            if ($value) {
                $permission_desc = ucwords(str_replace('_', ' ', $key));
                $permissions_list .= "<li>$permission_desc</li>";
            }
        }
        
        // Generate KSO ID for the admin
        $kso_id = 'KSO-ADM-' . str_pad($admin_id, 4, '0', STR_PAD_LEFT);
        
        // Update the admin record with KSO ID
        $stmt = $conn->prepare("UPDATE admins SET kso_id = ? WHERE id = ?");
        $stmt->execute([$kso_id, $admin_id]);
        
        // Prepare email data
        $emailData = [
            'name' => $name,
            'email' => $email,
            'password' => $_POST['password'], // Use original unhashed password
            'role' => $role,
            'admin_level' => "$admin_level - " . getAdminLevelDescription($admin_level),
            'permissions_list' => $permissions_list,
            'login_url' => getBaseUrl() . '/adminlte/login.php',
            'current_year' => date('Y'),
            'kso_id' => $kso_id
        ];
        
        // Send email using template
        $emailResult = $emailService->sendTemplate('admin-welcome', $emailData, $email, 'Welcome to KSO Chandigarh Admin Panel');
        
        if (!$emailResult) {
            // Log email failure but don't roll back the transaction
            $stmt = $conn->prepare("
                INSERT INTO admin_logs (admin_id, action, details, created_at)
                VALUES (?, 'email_failed', ?, CURRENT_TIMESTAMP)
            ");
            $stmt->execute([
                $_SESSION['admin_id'],
                'Failed to send welcome email to: ' . $email
            ]);
        }
    } catch (Exception $e) {
        // Log the email error but don't rollback the transaction
        error_log('Failed to send admin welcome email: ' . $e->getMessage());
    }
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Admin created successfully',
        'admin_id' => $admin_id,
        'email_sent' => $emailResult ?? false
    ]);
    
} catch (PDOException $e) {
    if (isset($conn)) {
        $conn->rollBack();
    }
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}

/**
 * Get admin level description
 */
function getAdminLevelDescription($level) {
    switch ($level) {
        case 4:
            return 'Basic';
        case 5:
            return 'Standard';
        case 6:
            return 'Advanced';
        case 7:
            return 'Senior';
        case 8:
            return 'Manager';
        case 9:
            return 'Super Admin';
        default:
            return 'Unknown';
    }
}

/**
 * Get base URL for the application
 */
function getBaseUrl() {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    
    // Remove any path components like /adminlte
    $baseUrl = "$protocol://$host";
    
    return $baseUrl;
}
?>
