<?php
/**
 * API Endpoint: Upload Product Image (Seller)
 * รองรับการอัปโหลดรูปภาพสินค้าจากเครื่องสำหรับผู้ขาย
 */

header('Content-Type: application/json; charset=utf-8');
require_once '../db.php';

// 1. ตรวจสอบ Method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

// 2. ตรวจสอบการ Authentication และ Permission (เฉพาะ Seller ที่ approved หรือ Admin)
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'กรุณาเข้าสู่ระบบก่อน']);
    exit;
}

$userRole = $_SESSION['role'] ?? 'user';
$sellerStatus = $_SESSION['seller_status'] ?? 'none';
$isAllowed = ($userRole === 'admin') || ($userRole === 'seller' && $sellerStatus === 'approved');

if (!$isAllowed) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'คุณไม่มีสิทธิ์อัปโหลดรูปภาพสินค้า (เฉพาะผู้ขายที่ได้รับการอนุมัติเท่านั้น)']);
    exit;
}

// 3. ตรวจสอบว่ามีการส่งไฟล์มาหรือไม่
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    $errorCode = $_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE;
    $errorMessage = 'ไม่พบไฟล์รูปภาพที่อัปโหลด';
    
    if ($errorCode === UPLOAD_ERR_INI_SIZE || $errorCode === UPLOAD_ERR_FORM_SIZE) {
        $errorMessage = 'ขนาดไฟล์ใหญ่เกินขีดจำกัดของเซิร์ฟเวอร์';
    }
    
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $errorMessage]);
    exit;
}

$file = $_FILES['image'];

// 4. ตรวจสอบขนาดไฟล์ (จำกัดไม่เกิน 5MB)
$maxFileSize = 5 * 1024 * 1024; // 5MB in bytes
if ($file['size'] > $maxFileSize) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'ขนาดไฟล์ต้องไม่เกิน 5MB']);
    exit;
}

// 5. ตรวจสอบ MIME type จริงของไฟล์
$allowedMimeTypes = [
    'image/jpeg' => 'jpg',
    'image/png'  => 'png',
    'image/webp' => 'webp',
    'image/jpg'  => 'jpg'
];

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file['tmp_name']);

if (!array_key_exists($mimeType, $allowedMimeTypes)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'ประเภทไฟล์ไม่ถูกต้อง (รองรับเฉพาะ JPG, PNG, WEBP เท่านั้น)']);
    exit;
}

// 6. ตรวจสอบ extension เพิ่มเติม
$originalExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$validExtensions = ['jpg', 'jpeg', 'png', 'webp'];
if (!in_array($originalExtension, $validExtensions)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'นามสกุลไฟล์ไม่ถูกต้อง']);
    exit;
}

// 7. จัดการโฟลเดอร์ uploads/products/
$uploadDir = __DIR__ . '/../uploads/products/';
if (!is_dir($uploadDir)) {
    if (!mkdir($uploadDir, 0755, true)) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'ไม่สามารถสร้างโฟลเดอร์สำหรับเก็บรูปภาพได้']);
        exit;
    }
}

// 8. ตั้งชื่อไฟล์ใหม่แบบสุ่ม ป้องกันชื่อซ้ำและ path traversal
$ext = $allowedMimeTypes[$mimeType];
$newFileName = 'prod_' . date('Ymd_His') . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
$targetPath = $uploadDir . $newFileName;

// 9. ย้ายไฟล์ไปยังโฟลเดอร์ปลายทาง
if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    // ส่ง path สัมพัทธ์สำหรับใช้งานในเว็บ เช่น uploads/products/prod_xxx.jpg
    $relativePath = 'uploads/products/' . $newFileName;
    echo json_encode([
        'success' => true,
        'message' => 'อัปโหลดรูปภาพสำเร็จ',
        'path' => $relativePath
    ]);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'เกิดข้อผิดพลาดในการบันทึกไฟล์รูปภาพ']);
}
?>
