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

require_once '../db/functions.php';
require_once '../db/products/Product.php';

$product = new Product($conn);
$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;
$deal_of_the_day = null;
$discountUrl = false;
$url = $_SERVER['REQUEST_URI'];
if (strpos($url, 'getdealoftheday') !== false) {
    $deal_of_the_day = 1;
} else if (strpos($url, 'getDiscount') !== false) {
    $discountUrl = true;
}
$sortByTime = $_GET['sortbytime'] ?? 'desc';
$sortByLike = $_GET['sortbylike'] ?? 'desc';

$name = $_POST['name'] ?? null;
$description = $_POST['description'] ?? null;
$price = $_POST['price'] ?? null;
$discount = $_POST['discount'] ?? 0;
$category_id = $_POST['category_id'] ?? null;
$stock = $_POST['stock'] ?? 0;
$material = $_POST['material'] ?? '';
$dimensions = $_POST['dimensions'] ?? '';
$weight = $_POST['weight'] ?? 0;


// مدیریت فایل تصویر آپلودی
if (isset($_FILES['image'])) {
    $targetDir = "../uploads/";
    if (!is_dir($targetDir))
        mkdir($targetDir, 0755, true);
    $fileName = basename($_FILES["image"]["name"]);
    $targetFilePath = $targetDir . $fileName;

    if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFilePath)) {
        $input['image_path'] = 'uploads/' . $fileName; // مسیر ذخیره در دیتابیس
        $image_path = $fileName;
    }

}

switch ($method) {
    case 'GET':
        if ($id) {
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode($product->get($id));
        } elseif ($deal_of_the_day) {
            header('Content-Type: application/json; charset=utf-8');

            echo json_encode($product->getDealOfTheDay());
        } elseif ($discountUrl) {
            header('Content-Type: application/json; charset=utf-8');

            echo json_encode($product->getDiscount());
        } else {
            header('Content-Type: application/json; charset=utf-8');


            echo json_encode($product->getAll($sortByTime, $sortByLike), JSON_UNESCAPED_UNICODE);
        }
        break;

    case 'POST':
        if (!empty($_FILES['photos'])) {
            if ($id) {
                $albums = $product->uploadAlbums($id, $_FILES['photos']);
                echo json_encode(['success' => true, 'albums' => $albums], JSON_UNESCAPED_UNICODE);
                exit();
            } else {
                echo json_encode(['error' => 'Product ID required']);
            }
        }
        $input = [
            'name' => $name,
            'description' => $description,
            'price' => $price,
            'discount' => $discount,
            'category_id' => $category_id,
            'stock' => $stock,
            'material' => $material,
            'dimensions' => $dimensions,
            'weight' => $weight,
            'image_path' => $image_path
        ];
        $newId = $product->create($input);
        echo json_encode(['id' => $newId]);
        break;

    case 'PUT':
        if ($id) {

            $product->update($id, $input);
            echo json_encode(['status' => 'updated']);
        }
        break;

    case 'DELETE':
        if ($id) {
            $product->delete($id);
            echo json_encode(['status' => 'deleted']);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}