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

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

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

$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 status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id   = filter_var($_POST['user_id'], FILTER_VALIDATE_INT);
    $full_name = trim($_POST['full_name'] ?? '');
    $phone     = trim($_POST['phone'] ?? '');

    if (!$user_id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid user ID']);
        exit();
    }

    // Validate phone if provided
    if (!empty($phone) && !preg_match('/^\+?[0-9]{7,15}$/', $phone)) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid phone number format']);
        exit();
    }

    try {
        // Check user exists
        $stmt = $pdo->prepare("SELECT username FROM users WHERE id = :user_id");
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            echo json_encode(['status' => '0', 'msg' => 'User not found']);
            exit();
        }

        // Update full_name and phone
        $stmt = $pdo->prepare("UPDATE users SET full_name = :full_name, phone = :phone, updated_at = NOW() WHERE id = :user_id");
        $stmt->execute([
            'full_name' => $full_name,
            'phone'     => !empty($phone) ? $phone : null,
            'user_id'   => $user_id
        ]);

        echo json_encode([
            'status' => '1',
            'msg'    => 'User ' . $user['username'] . '\'s profile has been updated successfully'
        ]);

    } catch (PDOException $e) {
        // Handle duplicate phone number
        if ($e->getCode() == 23000 && strpos($e->getMessage(), 'phone') !== false) {
            echo json_encode(['status' => '0', 'msg' => 'This phone number is already registered to another user']);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
        }
    }

} else {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
}
?>