grthtrhthjhtyjytjytkergtrhtrjytjerhrfh<?php
/**
 * Shoaib Printing Press - User Management API (PHP Version)
 * This script replaces the Node.js backend for cPanel environments.
 */

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// --- CONFIGURATION ---
// Try to load from .env file if it exists
if (file_exists(__DIR__ . '/.env')) {
    $lines = file(__DIR__ . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        list($name, $value) = explode('=', $line, 2);
        $name = trim($name);
        $value = trim($value);
        if (!getenv($name)) {
            putenv("$name=$value");
        }
    }
}

$supabaseUrl = getenv('SUPABASE_URL') ?: (getenv('VITE_SUPABASE_URL') ?: 'https://ntvxunsdiizqmodenvdx.supabase.co');
$serviceKey = getenv('SUPABASE_SERVICE_ROLE_KEY') ?: (getenv('MY_SUPABASE_SERVICE_ROLE_KEY') ?: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im50dnh1bnNkaWl6cW1vZGVudmR4Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3MTg3NjM4NywiZXhwIjoyMDg3NDUyMzg3fQ.3wP1t0dLy-k66d-6UD-DCMB1Ve12-tahgLGiCterlqw');

// Helper function for cURL requests to Supabase
function supabaseRequest($method, $path, $data = null) {
    global $supabaseUrl, $serviceKey;
    
    $url = rtrim($supabaseUrl, '/') . $path;
    $ch = curl_init($url);
    
    $headers = [
        "apikey: $serviceKey",
        "Authorization: Bearer $serviceKey",
        "Content-Type: application/json"
    ];
    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    if ($data) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return [
        'status' => $httpCode,
        'body' => json_decode($response, true)
    ];
}

$method = $_SERVER['REQUEST_METHOD'];
$pathInfo = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
$userId = ltrim($pathInfo, '/');

// Fallback to query parameter if PATH_INFO is empty
if (empty($userId) && isset($_GET['id'])) {
    $userId = $_GET['id'];
}

try {
    // --- GET ALL USERS ---
    if ($method === 'GET') {
        // 1. Fetch users from Auth
        $authRes = supabaseRequest('GET', '/auth/v1/admin/users');
        if ($authRes['status'] >= 400) throw new Exception("Auth Error: " . json_encode($authRes['body']));
        
        // 2. Fetch profiles from Database
        $dbRes = supabaseRequest('GET', '/rest/v1/profiles?select=*');
        if ($dbRes['status'] >= 400) throw new Exception("DB Error: " . json_encode($dbRes['body']));
        
        $users = $authRes['body']['users'];
        $profiles = $dbRes['body'];
        
        $merged = array_map(function($user) use ($profiles) {
            $profile = null;
            foreach ($profiles as $p) {
                if ($p['id'] === $user['id']) {
                    $profile = $p;
                    break;
                }
            }
            
            return [
                'id' => $user['id'],
                'email' => $user['email'],
                'full_name' => $profile['full_name'] ?? ($user['user_metadata']['full_name'] ?? ''),
                'role' => $profile['role'] ?? ($user['user_metadata']['role'] ?? 'Operator'),
                'permissions' => $profile['permissions'] ?? ($user['user_metadata']['permissions'] ?? new stdClass()),
                'created_at' => $user['created_at']
            ];
        }, $users);
        
        echo json_encode($merged);
    } 
    
    // --- CREATE USER ---
    elseif ($method === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $authData = [
            'email' => $input['email'],
            'password' => $input['password'],
            'email_confirm' => true,
            'user_metadata' => [
                'full_name' => $input['full_name'],
                'role' => $input['role'],
                'permissions' => $input['permissions']
            ]
        ];
        
        $res = supabaseRequest('POST', '/auth/v1/admin/users', $authData);
        if ($res['status'] >= 400) throw new Exception($res['body']['msg'] ?? "Failed to create user");
        
        echo json_encode($res['body']);
    }
    
    // --- UPDATE USER ---
    elseif ($method === 'PUT' && $userId) {
        $input = json_decode(file_get_contents('php://input'), true);
        
        // 1. Update Auth
        $updateData = [
            'user_metadata' => [
                'full_name' => $input['full_name'],
                'role' => $input['role'],
                'permissions' => $input['permissions']
            ]
        ];
        if (!empty($input['password'])) {
            $updateData['password'] = $input['password'];
        }
        
        $authRes = supabaseRequest('PUT', "/auth/v1/admin/users/$userId", $updateData);
        if ($authRes['status'] >= 400) throw new Exception($authRes['body']['msg'] ?? "Failed to update auth");
        
        // 2. Update Profile Table
        $profileData = [
            'full_name' => $input['full_name'],
            'role' => $input['role'],
            'permissions' => $input['permissions']
        ];
        $dbRes = supabaseRequest('PATCH', "/rest/v1/profiles?id=eq.$userId", $profileData);
        
        echo json_encode($authRes['body']);
    }
    
    // --- DELETE USER ---
    elseif ($method === 'DELETE' && $userId) {
        $res = supabaseRequest('DELETE', "/auth/v1/admin/users/$userId");
        if ($res['status'] >= 400) throw new Exception($res['body']['msg'] ?? "Failed to delete user");
        
        echo json_encode(['message' => 'User deleted successfully']);
    }
    
    else {
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_enc