<?php
// api/categories.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;
}

// Loyihaning root katalogi (mark2 root)
$BASE_DIR = realpath(__DIR__ . '/..');
if ($BASE_DIR === false) {
    $BASE_DIR = __DIR__ . '/..';
}

/**
 * Rasmni uploads/categories ichiga yuklaydi
 *  - $fieldName: input name (front: "image")
 *  - $oldPath: eski image_path ("/uploads/..." formatida)
 *
 * Natija:
 *  - Yangi rasm yuklangan bo'lsa: yangi image_path ("/uploads/categories/....jpg")
 *  - Fayl kelmagan bo'lsa: $oldPath qaytadi
 */
function handle_image_upload($fieldName, $oldPath = '', $BASE_DIR = '') {
    if (empty($_FILES[$fieldName]) || !is_array($_FILES[$fieldName])) {
        return $oldPath;
    }

    $file = $_FILES[$fieldName];

    if (!isset($file['error']) || $file['error'] === UPLOAD_ERR_NO_FILE) {
        return $oldPath;
    }

    if ($file['error'] !== UPLOAD_ERR_OK) {
        json_error('Rasm yuklashda xatolik (error code: ' . $file['error'] . ')');
    }

    $uploadDirDisk = rtrim($BASE_DIR, '/\\') . '/uploads/categories';
    if (!is_dir($uploadDirDisk)) {
        @mkdir($uploadDirDisk, 0775, true);
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if ($ext === '') {
        $ext = 'jpg';
    }

    try {
        $rnd = bin2hex(random_bytes(4));
    } catch (Throwable $e) {
        $rnd = uniqid();
    }

    $fileName   = 'cat_' . date('Ymd_His') . '_' . $rnd . '.' . $ext;
    $targetDisk = $uploadDirDisk . '/' . $fileName;

    if (!move_uploaded_file($file['tmp_name'], $targetDisk)) {
        json_error('Rasmni saqlab bo‘lmadi (move_uploaded_file).');
    }

    @chmod($targetDisk, 0664);

    // Eski faylni xavfsiz o'chirish (agar bo'lsa)
    if ($oldPath && strpos($oldPath, '/uploads/') === 0) {
        $oldDiskPath = rtrim($BASE_DIR, '/\\') . $oldPath;
        if (is_file($oldDiskPath)) {
            @unlink($oldDiskPath);
        }
    }

    $publicPath = '/uploads/categories/' . $fileName;
    return $publicPath;
}

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

try {
    // ===== LIST =====
    if ($action === 'list') {
        $stmt = $pdo->query("
          SELECT c.*
            FROM categories c
           ORDER BY c.id DESC
        ");
        $categories = $stmt->fetchAll();
        json_ok(['categories' => $categories]);
    }

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

        $id            = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $name          = trim($_POST['name'] ?? '');
        $is_active     = isset($_POST['is_active']) && $_POST['is_active'] == '1' ? 1 : 0;
        $existing_image = trim($_POST['existing_image'] ?? '');

        if ($name === '') {
            json_error('Kategoriya nomi majburiy.');
        }

        // Avval eski image_path
        $imagePath = $existing_image;

        // Yangi fayl yuborilgan bo'lsa – yuklaymiz
        $imagePath = handle_image_upload('image', $imagePath, $BASE_DIR);

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

        // Edit bo'lsa va imagePath bo'sh bo'lib qolsa – DB dan eski yo'lni fallback qilamiz
        if ($id > 0 && $imagePath === '') {
            $dbStmt = $pdo->prepare("SELECT image_path FROM categories WHERE id = ?");
            $dbStmt->execute([$id]);
            $dbRow = $dbStmt->fetch();
            if ($dbRow) {
                $imagePath = trim($dbRow['image_path'] ?? '');
            }
        }

        if ($id > 0) {
            // UPDATE
            $stmt = $pdo->prepare("
                UPDATE categories
                   SET name       = :name,
                       image_path = :img,
                       is_active  = :active,
                       updated_at = NOW()
                 WHERE id = :id
            ");
            $stmt->execute([
                ':name'   => $name,
                ':img'    => $imagePath,
                ':active' => $is_active,
                ':id'     => $id,
            ]);

            json_ok(['message' => 'Kategoriya tahrirlandi', 'id' => $id]);

        } else {
            // INSERT
            // created_by foreign key bilan muammo chiqmasligi uchun userni tekshiramiz
            $createdBy = current_user_id();
            if ($createdBy) {
                $check = $pdo->prepare("SELECT id FROM users WHERE id = ?");
                $check->execute([$createdBy]);
                if (!$check->fetchColumn()) {
                    // bunday user yo'q ekan – NULL qilamiz
                    $createdBy = null;
                }
            } else {
                $createdBy = null;
            }

            $stmt = $pdo->prepare("
                INSERT INTO categories
                  (name, image_path, created_at, created_by, is_active)
                VALUES
                  (:name, :img, NOW(), :created_by, :active)
            ");
            $stmt->execute([
                ':name'       => $name,
                ':img'        => $imagePath,
                ':created_by' => $createdBy,
                ':active'     => $is_active,
            ]);

            $newId = (int)$pdo->lastInsertId();
            json_ok(['message' => 'Yangi kategoriya 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 categories WHERE id = ?");
        $rowStmt->execute([$id]);
        $row = $rowStmt->fetch();
        if (!$row) {
            json_error('Kategoriya topilmadi', 404);
        }

        $newState = $row['is_active'] ? 0 : 1;
        $upd = $pdo->prepare("UPDATE categories 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');
        }

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

        try {
            $del = $pdo->prepare("DELETE FROM categories WHERE id = ?");
            $del->execute([$id]);
        } catch (PDOException $ex) {
            if ($ex->getCode() === '23000') {
                json_error(
                    'Bu kategoriya boshqa jadvallarda ishlatilgan (foreign key). Avval bog‘liq zapislarni ko‘rib chiqing.',
                    409
                );
            }
            throw $ex;
        }

        // Rasmni ham ixtiyoriy o'chiramiz
        if (!empty($row['image_path']) && strpos($row['image_path'], '/uploads/') === 0) {
            $oldDiskPath = rtrim($BASE_DIR, '/\\') . $row['image_path'];
            if (is_file($oldDiskPath)) {
                @unlink($oldDiskPath);
            }
        }

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

    // Hech bir actionga tushmasa
    json_error('Noto‘g‘ri action', 400);

} catch (Throwable $e) {
    // Debug uchun xatoni qaytaryapmiz, xohlasang keyin umumiy "Server xatosi"ga almashtirib qo‘yasan
    json_error('Server xatosi: ' . $e->getMessage(), 500);
}
