<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard_web.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

if (!isset($_POST['category_id'], $_FILES['image'])) {
    Response::error('category_id is required');
}

$categoryId = (int) $_POST['category_id'];
if ($categoryId <= 0) {
    Response::error('Invalid category id');
}

$imageAlt = isset($_POST['image_alt']) ? trim($_POST['image_alt']) : null;

$file = $_FILES['image'];
if ($file['error'] !== UPLOAD_ERR_OK) {
    Response::error('Image upload failed');
}

/* MIME CHECK */
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $file['tmp_name']);

$allowed = ['image/jpeg','image/png','image/webp'];
if (!in_array($mime, $allowed, true)) {
    Response::error('Invalid image type');
}

/* PATH */
$baseDir = __DIR__ . '/../../../uploads/categories/';
$catDir  = $baseDir . $categoryId . '/';

if (!is_dir($catDir)) {
    mkdir($catDir, 0775, true);
}

$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = 'category.' . $ext;

$fullPath = $catDir . $filename;
$dbPath   = '/uploads/categories/' . $categoryId . '/' . $filename;

/* REMOVE OLD IMAGE */
$stmt = $db->prepare("SELECT image_path FROM retail_categories WHERE id=:id");
$stmt->execute(['id'=>$categoryId]);
$old = $stmt->fetchColumn();

if ($old) {
    $oldFile = __DIR__ . '/../../../' . ltrim($old, '/');
    if (is_file($oldFile)) unlink($oldFile);
}

/* SAVE FILE */
if (!move_uploaded_file($file['tmp_name'], $fullPath)) {
    Response::error('Failed to save image');
}

/* UPDATE DB */
$stmt = $db->prepare("
    UPDATE retail_categories
    SET image_path = :path,
        image_alt  = :alt,
        updated_at = NOW()
    WHERE id = :id
");
$stmt->execute([
    'path' => $dbPath,
    'alt'  => $imageAlt,
    'id'   => $categoryId
]);

Response::success('Image uploaded', [
    'image_path' => $dbPath,
    'image_alt'  => $imageAlt
]);
