<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';
require_once __DIR__ . '/../../core/Slug.php';

$db = Database::getInstance();
$data = json_decode(file_get_contents('php://input'), true);

/**
 * REQUIRED FIELDS
 */
Validator::required($data, [
    'product_id',
    'product_name',
    'category_id',
    'short_description',
    'full_description',
    'brochure_file'
]);

$productId   = (int)$data['product_id'];
$productName = trim($data['product_name']);
$categoryId  = (int)$data['category_id'];
$shortDesc   = trim($data['short_description']);
$fullDesc    = trim($data['full_description']);
$brochure    = trim($data['brochure_file']);

$primarySleepId   = $data['primary_sleep_id'] ?? null;
$secondarySleepId = $data['secondary_sleep_id'] ?? null;
$updateSlug       = !empty($data['update_slug']) && $data['update_slug'] === true;

/**
 * VALIDATION
 */
Validator::minLength($productName, 2, 'product_name');
Validator::minLength($shortDesc, 10, 'short_description');
Validator::minLength($fullDesc, 20, 'full_description');

if (!preg_match('/\.pdf$/i', $brochure)) {
    Response::error('Brochure must be a PDF file', 422);
}

/**
 * CHECK PRODUCT EXISTS
 */
$stmt = $db->prepare("SELECT id FROM retail_products WHERE id = :id");
$stmt->execute(['id' => $productId]);

if (!$stmt->fetch()) {
    Response::error('Retail product not found', 404);
}

/**
 * OPTIONAL SLUG UPDATE (SAFE)
 */
if ($updateSlug) {
    $slug = Slug::unique($productName, 'retail_products', $productId);
}

/**
 * BUILD UPDATE QUERY
 */
$sql = "
UPDATE retail_products
SET
    product_name = :name,
    category_id = :category,
    primary_sleep_id = :primary_sleep_id,
    secondary_sleep_id = :secondary_sleep_id,
    short_description = :short_desc,
    full_description = :full_desc,
    brochure_file = :brochure,
    updated_by = :updated_by,
    updated_at = NOW()
";

if ($updateSlug) {
    $sql .= ", slug = :slug";
}

$sql .= " WHERE id = :id";

$stmt = $db->prepare($sql);

$params = [
    'name'               => $productName,
    'category'           => $categoryId,
    'primary_sleep_id'   => $primarySleepId,
    'secondary_sleep_id' => $secondarySleepId,
    'short_desc'         => $shortDesc,
    'full_desc'          => $fullDesc,
    'brochure'           => $brochure,
    'updated_by'         => $_SESSION['employee_id'],
    'id'                 => $productId
];

if ($updateSlug) {
    $params['slug'] = $slug;
}

$stmt->execute($params);

Response::success('Retail product updated successfully');
