<?php
// api/products.php
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth_stub.php';

session_start();

function json_error($message, $code = 400) {
    http_response_code($code);
    echo json_encode(['status' => 'error', 'message' => $message], JSON_UNESCAPED_UNICODE);
    exit;
}

function json_ok($data = []) {
    echo json_encode(array_merge(['status' => 'ok'], $data), JSON_UNESCAPED_UNICODE);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

try {
    /** @var PDO $pdo */

    // ===== LIST =====
    if ($action === 'list') {
        $stmt = $pdo->query("
          SELECT p.*, c.name AS category_name
            FROM products p
            LEFT JOIN categories c ON c.id = p.category_id
           ORDER BY p.id DESC
        ");
        $products = $stmt->fetchAll();
        json_ok(['products' => $products]);
    }

    // ===== SAVE (CREATE/UPDATE) =====
    if ($action === 'save') {
        if ($method !== 'POST') {
            json_error('POST bo‘lishi kerak', 405);
        }

        $id          = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $category_id = (int)($_POST['category_id'] ?? 0);
        $name        = trim($_POST['name'] ?? '');
        $block_unit  = (int)($_POST['product_block_unit'] ?? 0);
        $gtin        = trim($_POST['gtin_number'] ?? '');
        $gtin2       = trim($_POST['gtin2_number'] ?? '');
        $generate    = $_POST['generate_type'] ?? 'manual';

        // is_active = checkbox => "on"/(bo'sh)
        $is_active   = !empty($_POST['is_active']) ? 1 : 0;

        if (!$category_id || $name === '' || !$block_unit || $gtin === '') {
            json_error('Kategoriya, mahsulot nomi, blok unit va GTIN majburiy.');
        }
        if (!in_array($generate, ['manual', 'auto'], true)) {
            $generate = 'manual';
        }

        // Eski rasm (update uchun)
        $oldImage = null;
        if ($id > 0) {
            $stOld = $pdo->prepare("SELECT product_image FROM products WHERE id = ?");
            $stOld->execute([$id]);
            $rowOld = $stOld->fetch();
            if ($rowOld) {
                $oldImage = $rowOld['product_image'];
            }
        }

        // Fayl yuklash
        $imagePath = $oldImage; // default: eski rasm
        if (!empty($_FILES['product_image']['name'])) {
            $uploadDir = __DIR__ . '/../uploads/products';
            if (!is_dir($uploadDir)) {
                @mkdir($uploadDir, 0777, true);
            }

            $ext = pathinfo($_FILES['product_image']['name'], PATHINFO_EXTENSION);
            $ext = strtolower($ext ?: 'jpg');

            // random_bytes PHP 7+ da bor, bo'lmasa uniqid ishlatamiz
            if (function_exists('random_bytes')) {
                $rand = bin2hex(random_bytes(4));
            } else {
                $rand = bin2hex(substr(uniqid('', true), -4));
            }

            $fileName = 'prod_' . time() . '_' . $rand . '.' . $ext;
            $target   = $uploadDir . '/' . $fileName;

            if (!is_uploaded_file($_FILES['product_image']['tmp_name'])) {
                json_error('Rasm fayli noto‘g‘ri yuklandi.');
            }

            if (!move_uploaded_file($_FILES['product_image']['tmp_name'], $target)) {
                json_error('Rasm faylini saqlashda xatolik.');
            }

            $imagePath = '/uploads/products/' . $fileName;

            // Xohlasang eski rasmni ham o‘chirishing mumkin
            // if ($oldImage && substr($oldImage, 0, 18) === '/uploads/products/') {
            //     $oldFull = __DIR__ . '/..' . $oldImage;
            //     if (is_file($oldFull)) @unlink($oldFull);
            // }
        }

        // Yangi mahsulot uchun rasm majburiy
        if ($id <= 0 && !$imagePath) {
            json_error('Yangi mahsulot uchun rasm fayli majburiy.');
        }

        if ($id > 0) {
            // UPDATE
            $stmt = $pdo->prepare("
                UPDATE products
                   SET category_id        = :category_id,
                       name               = :name,
                       product_block_unit = :block_unit,
                       gtin_number        = :gtin,
                       gtin2_number       = :gtin2,
                       product_image      = :img,
                       generate_type      = :gen,
                       is_active          = :active,
                       updated_at         = NOW()
                 WHERE id = :id
            ");
            $stmt->execute([
                ':category_id' => $category_id,
                ':name'        => $name,
                ':block_unit'  => $block_unit,
                ':gtin'        => $gtin,
                ':gtin2'       => $gtin2 ?: null,
                ':img'         => $imagePath,
                ':gen'         => $generate,
                ':active'      => $is_active,
                ':id'          => $id,
            ]);
            json_ok(['message' => 'Mahsulot tahrirlandi', 'id' => $id]);

        } else {
            // INSERT
            $stmt = $pdo->prepare("
                INSERT INTO products
                (category_id, name, product_block_unit, gtin_number, gtin2_number, product_image,
                 generate_type, created_at, created_by, is_active)
                VALUES (:category_id, :name, :block_unit, :gtin, :gtin2, :img,
                        :gen, NOW(), :created_by, :active)
            ");
            $stmt->execute([
                ':category_id' => $category_id,
                ':name'        => $name,
                ':block_unit'  => $block_unit,
                ':gtin'        => $gtin,
                ':gtin2'       => $gtin2 ?: null,
                ':img'         => $imagePath,
                ':gen'         => $generate,
                // agar current_user_id() bo'lmasa ham 1 qilib qo'yamiz
                ':created_by'  => current_user_id() ?: 1,
                ':active'      => $is_active,
            ]);
            $newId = (int)$pdo->lastInsertId();
            json_ok(['message' => 'Yangi mahsulot qo‘shildi', 'id' => $newId]);
        }
    }

    // ===== TOGGLE is_active =====
    if ($action === 'toggle') {
        if ($method !== 'POST') {
            json_error('POST bo‘lishi kerak', 405);
        }
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) {
            json_error('Noto‘g‘ri ID');
        }

        $rowStmt = $pdo->prepare("SELECT is_active FROM products WHERE id = ?");
        $rowStmt->execute([$id]);
        $row = $rowStmt->fetch();
        if (!$row) {
            json_error('Mahsulot topilmadi', 404);
        }

        $newState = $row['is_active'] ? 0 : 1;
        $upd = $pdo->prepare("UPDATE products SET is_active = ?, updated_at = NOW() WHERE id = ?");
        $upd->execute([$newState, $id]);

        json_ok(['message' => 'Holat yangilandi', 'id' => $id, 'is_active' => $newState]);
    }

    // ===== DELETE =====
    if ($action === 'delete') {
        if ($method !== 'POST') {
            json_error('POST bo‘lishi kerak', 405);
        }
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) {
            json_error('Noto‘g‘ri ID');
        }

        // Mahsulot mavjudmi?
        $rowStmt = $pdo->prepare("SELECT id, name, product_image FROM products WHERE id = ?");
        $rowStmt->execute([$id]);
        $row = $rowStmt->fetch();
        if (!$row) {
            json_error('Mahsulot topilmadi', 404);
        }

        // Referencelar (agar kerak bo'lsa, o'zing qo'shasan)
        $refChecks = [
            // ['table' => 'mark_logs',   'column' => 'product_id', 'label' => 'markirovka loglari'],
            // ['table' => 'mark_blocks', 'column' => 'product_id', 'label' => 'markirovka bloklari'],
        ];

        foreach ($refChecks as $ref) {
            $sql = "SELECT COUNT(*) AS cnt FROM {$ref['table']} WHERE {$ref['column']} = :id LIMIT 1";
            $st  = $pdo->prepare($sql);
            $st->execute([':id' => $id]);
            $cnt = (int)$st->fetchColumn();
            if ($cnt > 0) {
                json_error(
                    'Bu mahsulot ' . ($ref['label'] ?? $ref['table']) .
                    ' jadvalida ishlatilgan. O‘chirishdan oldin bog‘liq yozuvlarni ko‘rib chiqing.',
                    409
                );
            }
        }

        // O‘chirish
        $del = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $del->execute([$id]);

        // Rasm faylini ham o‘chirib yuboramiz (PHP 7 bilan mos)
        if (!empty($row['product_image']) &&
            substr($row['product_image'], 0, 18) === '/uploads/products/') {

            $fullPath = __DIR__ . '/..' . $row['product_image'];
            if (is_file($fullPath)) {
                @unlink($fullPath);
            }
        }

        json_ok([
            'message' => 'Mahsulot o‘chirildi',
            'id'      => $id,
            'name'    => $row['name']
        ]);
    }

    // Noto‘g‘ri action
    json_error('Noto‘g‘ri action', 400);

} catch (Throwable $e) {
    // Debug uchun: hozircha aniq xabarni ko'rsatamiz
    // Productionga chiqqanda bu joyni yana "Server xatosi" ga qaytarib qo'yasan.
    json_error('Server xatosi: ' . $e->getMessage(), 500);
}
