<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    // 1. Authenticate Requesting User
    $requester_id = Auth::check();
    
    // 2. Determine Target User
    $target_user_id = $requester_id;
    if (isset($_POST['target_user_id'])) {
        // Check if requester is Admin to allow editing others
        $stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?");
        $stmt->execute([$requester_id]);
        $role = $stmt->fetchColumn();
        
        if (!in_array($role, ['admin', 'super_admin'])) {
            throw new Exception("Unauthorized to edit other users.");
        }
        $target_user_id = (int)$_POST['target_user_id'];
    }

    // 3. Validation
    if (!isset($_FILES['image'])) throw new Exception("No file uploaded");
    if (!isset($_POST['type']) || !in_array($_POST['type'], ['avatar', 'cover'])) {
        throw new Exception("Invalid image type (must be 'avatar' or 'cover').");
    }

    $type = $_POST['type']; // 'avatar' or 'cover'
    $file = $_FILES['image'];
    
    $allowed_types = ['image/jpeg', 'image/png', 'image/webp', 'image/jpg'];
    if (!in_array($file['type'], $allowed_types)) {
        throw new Exception("Invalid file type. Only JPG, PNG, WEBP allowed.");
    }
    
    if ($file['size'] > 5 * 1024 * 1024) throw new Exception("File too large. Max 5MB.");

    // 4. Prepare Directory
    $folder_name = ($type === 'avatar') ? 'avatars' : 'covers';
    $upload_dir = "../../uploads/$folder_name/";
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = "user_{$target_user_id}_" . time() . ".$ext";
    $target_path = $upload_dir . $filename;
    
    // 5. Move File & Update DB
    if (move_uploaded_file($file['tmp_name'], $target_path)) {
        // Construct Public URL
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'];
        $base_url = str_replace('/server/api/upload', '', dirname($_SERVER['SCRIPT_NAME'])); // e.g. /Juuvix_Shop/KLKAPP TEST
        
        $public_url = "$protocol://$host$base_url/server/uploads/$folder_name/" . $filename;
        
        // Update specific column (user_avatar or user_cover)
        // Map 'avatar' -> 'user_avatar', 'cover' -> 'user_cover'
        $column = ($type === 'avatar') ? 'user_avatar' : 'user_cover';
        
        $stmt = $pdo->prepare("UPDATE i_users SET $column = ? WHERE iuid = ?");
        $stmt->execute([$public_url, $target_user_id]);
        
        echo json_encode([
            'success' => true,
            'message' => ucfirst($type) . ' updated successfully',
            'url' => $public_url
        ]);
    } else {
        throw new Exception("Failed to save file on server.");
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
