<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

// Load config
$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Verify admin access
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    echo json_encode(['status' => '0', 'msg' => 'User not authenticated']);
    exit();
}

try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id AND is_admin = 1 LIMIT 1");
    $stmt->execute([':id' => $user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Database error']);
    exit();
}

if (!$user) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized - Admin access required']);
    exit();
}

// Handle request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$action = trim($_POST['action'] ?? '');

// ─── ACTION: save ─────────────────────────────────────────────────
if ($action === 'save') {
    $username = trim($_POST['username'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $fullname = trim($_POST['fullname'] ?? '');
    $password = trim($_POST['password'] ?? '');

    // Validation
    if (!$username || !$email || !$fullname) {
        echo json_encode(['status' => '0', 'msg' => 'Missing required fields']);
        exit();
    }

    if (strlen($username) < 3 || strlen($username) > 50) {
        echo json_encode(['status' => '0', 'msg' => 'Username must be 3-50 characters']);
        exit();
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid email address']);
        exit();
    }

    if (strlen($fullname) < 2 || strlen($fullname) > 100) {
        echo json_encode(['status' => '0', 'msg' => 'Full name must be 2-100 characters']);
        exit();
    }

    // Check username uniqueness
    try {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = :username AND id != :id LIMIT 1");
        $stmt->execute([':username' => $username, ':id' => $user_id]);
        if ($stmt->fetch()) {
            echo json_encode(['status' => '0', 'msg' => 'Username already exists']);
            exit();
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error checking username']);
        exit();
    }

    // Check email uniqueness
    try {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = :email AND id != :id LIMIT 1");
        $stmt->execute([':email' => $email, ':id' => $user_id]);
        if ($stmt->fetch()) {
            echo json_encode(['status' => '0', 'msg' => 'Email already exists']);
            exit();
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error checking email']);
        exit();
    }

    // Update profile
    try {
        if ($password) {
            // Validate password strength
            if (strlen($password) < 8) {
                echo json_encode(['status' => '0', 'msg' => 'Password must be at least 8 characters']);
                exit();
            }
            if (!preg_match('/[A-Z]/', $password) || !preg_match('/[a-z]/', $password) || !preg_match('/[0-9]/', $password)) {
                echo json_encode(['status' => '0', 'msg' => 'Password must contain uppercase, lowercase, and numbers']);
                exit();
            }

            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare(
                "UPDATE users SET username = :username, email = :email, full_name = :fullname, password = :password WHERE id = :id"
            );
            $stmt->execute([
                ':username' => $username,
                ':email'    => $email,
                ':fullname' => $fullname,
                ':password' => $hashed_password,
                ':id'       => $user_id
            ]);
        } else {
            $stmt = $pdo->prepare(
                "UPDATE users SET username = :username, email = :email, full_name = :fullname WHERE id = :id"
            );
            $stmt->execute([
                ':username' => $username,
                ':email'    => $email,
                ':fullname' => $fullname,
                ':id'       => $user_id
            ]);
        }

        // Log activity
        error_log("[ADMIN] Admin ID {$user_id} updated profile - Username: {$username}, Email: {$email}");

        echo json_encode(['status' => '1', 'msg' => 'Profile updated successfully!']);
    } catch (PDOException $e) {
        error_log("Admin profile update error: " . $e->getMessage());
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// ─── UNKNOWN ACTION ───────────���───────────────────────────────────
echo json_encode(['status' => '0', 'msg' => 'Unknown action']);