<?php
// api/clients.php  — customers jadvali bilan ishlaydi
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 {

    // ==== RO'YXAT (customers) ====
    if ($action === 'list') {
        $stmt = $pdo->query("
          SELECT id,
                 name,
                 contact_person,
                 phone,
                 email,
                 address,
                 region,
                 city,
                 inn,
                 note,
                 is_active,
                 created_at,
                 updated_at
            FROM customers
           ORDER BY id DESC
        ");
        $rows = $stmt->fetchAll();

        // front-end nomini o‘zgartirmaymiz: res.clients
        json_ok(['clients' => $rows]);
    }

    // ==== CREATE / UPDATE (customers) ====
    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'] ?? '');
        $contactPerson  = trim($_POST['contact_person'] ?? '');
        $phone          = trim($_POST['phone'] ?? '');
        $email          = trim($_POST['email'] ?? '');   // front-endda hozir yo‘q, lekin optional
        $address        = trim($_POST['address'] ?? '');
        $region         = trim($_POST['region'] ?? '');
        $city           = trim($_POST['city'] ?? '');
        $inn            = trim($_POST['inn'] ?? '');
        $note           = trim($_POST['note'] ?? '');
        $is_active      = isset($_POST['is_active']) && $_POST['is_active'] == '1' ? 1 : 0;

        if ($name === '' || $phone === '') {
            json_error('Mijoz nomi va telefon majburiy.');
        }

        if ($id > 0) {
            // UPDATE customers
            $stmt = $pdo->prepare("
                UPDATE customers
                   SET name           = :name,
                       contact_person = :contact_person,
                       phone          = :phone,
                       email          = :email,
                       address        = :address,
                       region         = :region,
                       city           = :city,
                       inn            = :inn,
                       note           = :note,
                       is_active      = :active,
                       updated_at     = NOW()
                 WHERE id = :id
            ");
            $stmt->execute([
                ':name'           => $name,
                ':contact_person' => $contactPerson !== '' ? $contactPerson : null,
                ':phone'          => $phone,
                ':email'          => $email !== '' ? $email : null,
                ':address'        => $address !== '' ? $address : null,
                ':region'         => $region !== '' ? $region : null,
                ':city'           => $city !== '' ? $city : null,
                ':inn'            => $inn !== '' ? $inn : null,
                ':note'           => $note !== '' ? $note : null,
                ':active'         => $is_active,
                ':id'             => $id,
            ]);

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

        } else {
            // INSERT customers
            $createdBy = current_user_id();

            // Agar created_by NOT NULL + FK bo‘lsa, fallback: 1-admin
            if (!$createdBy) {
                $createdBy = 1;
            }

            $stmt = $pdo->prepare("
                INSERT INTO customers
                  (name,
                   contact_person,
                   phone,
                   email,
                   address,
                   region,
                   city,
                   inn,
                   note,
                   created_at,
                   created_by,
                   is_active)
                VALUES
                  (:name,
                   :contact_person,
                   :phone,
                   :email,
                   :address,
                   :region,
                   :city,
                   :inn,
                   :note,
                   NOW(),
                   :created_by,
                   :active)
            ");
            $stmt->execute([
                ':name'           => $name,
                ':contact_person' => $contactPerson !== '' ? $contactPerson : null,
                ':phone'          => $phone,
                ':email'          => $email !== '' ? $email : null,
                ':address'        => $address !== '' ? $address : null,
                ':region'         => $region !== '' ? $region : null,
                ':city'           => $city !== '' ? $city : null,
                ':inn'            => $inn !== '' ? $inn : null,
                ':note'           => $note !== '' ? $note : null,
                ':created_by'     => $createdBy,
                ':active'         => $is_active,
            ]);

            $newId = (int)$pdo->lastInsertId();
            json_ok(['message' => 'Yangi mijoz qo‘shildi', 'id' => $newId]);
        }
    }

    // ==== ACTIVE/INACTIVE TOGGLE (customers) ====
    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 customers WHERE id = ?");
        $rowStmt->execute([$id]);
        $row = $rowStmt->fetch();
        if (!$row) {
            json_error('Mijoz topilmadi', 404);
        }

        $newState = $row['is_active'] ? 0 : 1;

        $upd = $pdo->prepare("
            UPDATE customers
               SET is_active  = ?,
                   updated_at = NOW()
             WHERE id = ?
        ");
        $upd->execute([$newState, $id]);

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

    // ==== DELETE (customers) ====
    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');
        }

        // Avval mavjudligini tekshiramiz
        $rowStmt = $pdo->prepare("SELECT id, name FROM customers WHERE id = ?");
        $rowStmt->execute([$id]);
        $row = $rowStmt->fetch();
        if (!$row) {
            json_error('Mijoz topilmadi', 404);
        }

        try {
            $del = $pdo->prepare("DELETE FROM customers WHERE id = ?");
            $del->execute([$id]);

        } catch (PDOException $e) {
            // Agar FK bo‘lsa (masalan, buyurtmalar jadvali bog‘langan bo‘lsa)
            if ($e->getCode() === '23000') {
                json_error(
                    'Bu mijoz boshqa jadvalda ishlatilgan (masalan, buyurtmalar logida). O‘chirib bo‘lmaydi.',
                    409
                );
            }
            throw $e;
        }

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

    // Hech qaysi action tushmasa:
    json_error('Noto‘g‘ri action', 400);

} catch (Throwable $e) {
    // Debug uchun xabarni ham qaytaryapmiz
    json_error('Server xatosi: ' . $e->getMessage(), 500);
}
