<?php
session_start();
require_once '../config/config.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
$admin_id = $_POST['admin_id'] ?? '';
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$role = $_POST['role'] ?? '';
$admin_level = isset($_POST['admin_level']) ? (int)$_POST['admin_level'] : null;
$status = $_POST['status'] ?? '';
$password = $_POST['password'] ?? ''; // Optional, only if changing password

// Validate required fields
if (empty($admin_id) || empty($name) || empty($email) || empty($role) || $admin_level === null || empty($status)) {
    echo json_encode(['success' => false, 'message' => 'All fields are required except password']);
    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 admin exists
    $stmt = $conn->prepare("SELECT * FROM admins WHERE id = ?");
    $stmt->execute([$admin_id]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$admin) {
        $conn->rollBack();
        echo json_encode(['success' => false, 'message' => 'Admin not found']);
        exit();
    }
    
    // Check if email already exists for another admin
    $stmt = $conn->prepare("SELECT COUNT(*) FROM admins WHERE email = ? AND id != ?");
    $stmt->execute([$email, $admin_id]);
    $emailExists = $stmt->fetchColumn() > 0;
    
    if ($emailExists) {
        $conn->rollBack();
        echo json_encode(['success' => false, 'message' => 'Email already exists for another admin']);
        exit();
    }
    
    // Don't allow reducing the level of the last super admin
    if ($admin_level < 9 && $admin['admin_level'] >= 9) {
        // Check if this is the last super admin
        $stmt = $conn->prepare("SELECT COUNT(*) FROM admins WHERE admin_level >= 9 AND id != ?");
        $stmt->execute([$admin_id]);
        $superAdminCount = $stmt->fetchColumn();
        
        if ($superAdminCount === 0) {
            $conn->rollBack();
            echo json_encode(['success' => false, 'message' => 'Cannot downgrade the last super admin']);
            exit();
        }
    }
    
    // Prepare update SQL based on whether password is being changed
    if (!empty($password)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $sql = "
            UPDATE admins SET
                name = ?,
                email = ?,
                password = ?,
                role = ?,
                admin_level = ?,
                status = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        ";
        $params = [$name, $email, $hashed_password, $role, $admin_level, $status, $admin_id];
    } else {
        $sql = "
            UPDATE admins SET
                name = ?,
                email = ?,
                role = ?,
                admin_level = ?,
                status = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        ";
        $params = [$name, $email, $role, $admin_level, $status, $admin_id];
    }
    
    // Update admin in the database
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    
    // Update permissions if provided
    if (isset($_POST['permissions']) && is_array($_POST['permissions'])) {
        // Delete existing permissions
        $stmt = $conn->prepare("DELETE FROM admin_permissions WHERE admin_id = ?");
        $stmt->execute([$admin_id]);
        
        // Insert new permissions
        $stmt = $conn->prepare("
            INSERT INTO admin_permissions (
                admin_id, permission_key, is_granted, created_at, updated_at
            ) VALUES (
                ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
            )
        ");
        
        foreach ($_POST['permissions'] as $key => $value) {
            $stmt->execute([
                $admin_id,
                $key,
                $value ? 1 : 0
            ]);
        }
    }
    
    // Log the action
    $stmt = $conn->prepare("
        INSERT INTO admin_logs (admin_id, action, details, created_at)
        VALUES (?, 'update_admin', ?, CURRENT_TIMESTAMP)
    ");
    $stmt->execute([
        $_SESSION['admin_id'],
        'Updated admin: ' . $name . ' (ID: ' . $admin_id . ')'
    ]);
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Admin updated successfully'
    ]);
    
} catch (PDOException $e) {
    if (isset($conn)) {
        $conn->rollBack();
    }
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
