<?php
// api/sales.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'];
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

try {

    // === 1) RO'YXAT (LIST) ===
    if ($action === 'list') {
        $page    = max(1, (int)($_GET['page'] ?? 1));
        $perPage = (int)($_GET['per_page'] ?? 20);
        if ($perPage <= 0)  $perPage = 20;
        if ($perPage > 200) $perPage = 200;
        $offset  = ($page - 1) * $perPage;

        $clientId = (int)($_GET['client_id'] ?? 0);
        $status   = $_GET['status'] ?? '';
        $dateFrom = $_GET['date_from'] ?? '';
        $dateTo   = $_GET['date_to'] ?? '';
        $search   = trim($_GET['search'] ?? '');

        $where  = [];
        $params = [];

        if ($clientId > 0) {
            $where[] = 'o.client_id = :client_id';
            $params[':client_id'] = $clientId;
        }
        if ($status !== '' && in_array($status, ['draft','confirmed','cancelled'], true)) {
            $where[] = 'o.status = :status';
            $params[':status'] = $status;
        }
        if ($dateFrom !== '') {
            $where[] = 'o.order_date >= :date_from';
            $params[':date_from'] = $dateFrom;
        }
        if ($dateTo !== '') {
            $where[] = 'o.order_date <= :date_to';
            $params[':date_to'] = $dateTo;
        }
        if ($search !== '') {
            $where[] = '(c.name LIKE :q OR o.id = :id_q)';
            $params[':q']    = '%' . $search . '%';
            $params[':id_q'] = ctype_digit($search) ? (int)$search : 0;
        }

        $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

        // Jami
        $countSql = "
          SELECT COUNT(*)
            FROM sales_orders o
            JOIN clients c ON c.id = o.client_id
          $whereSql
        ";
        $cnt = $pdo->prepare($countSql);
        foreach ($params as $k => $v) {
            $cnt->bindValue($k, $v);
        }
        $cnt->execute();
        $total = (int)$cnt->fetchColumn();

        // Asosiy select (itemlar soni bilan)
        $listSql = "
          SELECT
            o.id,
            o.order_date,
            o.status,
            o.total_amount,
            o.client_id,
            c.name AS client_name,
            o.note,
            o.created_at,
            o.updated_at,
            COUNT(i.id) AS item_count
          FROM sales_orders o
            JOIN clients c ON c.id = o.client_id
       LEFT JOIN sales_items i ON i.order_id = o.id
          $whereSql
          GROUP BY o.id
          ORDER BY o.order_date DESC, o.id DESC
          LIMIT :limit OFFSET :offset
        ";
        $stmt = $pdo->prepare($listSql);
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v);
        }
        $stmt->bindValue(':limit',  $perPage, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset,  PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll();

        $pageCount = $total > 0 ? (int)ceil($total / $perPage) : 1;

        json_ok([
            'orders' => $rows,
            'pagination' => [
                'total'      => $total,
                'page'       => $page,
                'per_page'   => $perPage,
                'page_count' => $pageCount
            ]
        ]);
    }

    // === 2) Bitta orderni olish (GET) ===
    if ($action === 'get') {
        $id = (int)($_GET['id'] ?? 0);
        if ($id <= 0) {
            json_error('Noto‘g‘ri ID', 400);
        }

        $hdrSql = "
          SELECT
            o.*,
            c.name AS client_name
          FROM sales_orders o
            JOIN clients c ON c.id = o.client_id
         WHERE o.id = :id
        ";
        $hdr = $pdo->prepare($hdrSql);
        $hdr->execute([':id' => $id]);
        $order = $hdr->fetch();
        if (!$order) {
            json_error('Sotuv topilmadi', 404);
        }

        $itemsSql = "
          SELECT
            i.id,
            i.product_id,
            p.name AS product_name,
            i.quantity,
            i.unit_price,
            i.total_price
          FROM sales_items i
            JOIN products p ON p.id = i.product_id
         WHERE i.order_id = :id
         ORDER BY i.id ASC
        ";
        $it = $pdo->prepare($itemsSql);
        $it->execute([':id' => $id]);
        $items = $it->fetchAll();

        json_ok([
            'order' => $order,
            'items' => $items
        ]);
    }

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

        $id        = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $client_id = (int)($_POST['client_id'] ?? 0);
        $order_date = $_POST['order_date'] ?? '';
        $status    = $_POST['status'] ?? 'confirmed';
        $note      = trim($_POST['note'] ?? '');
        $itemsJson = $_POST['items_json'] ?? '';

        if ($client_id <= 0 || $order_date === '') {
            json_error('Mijoz va sana majburiy.');
        }
        if (!in_array($status, ['draft','confirmed','cancelled'], true)) {
            $status = 'confirmed';
        }
        if ($itemsJson === '') {
            json_error('Tarkib (items) bo‘sh.', 400);
        }

        $items = json_decode($itemsJson, true);
        if (!is_array($items) || !count($items)) {
            json_error('Tarkib noto‘g‘ri formatda.', 400);
        }

        $cleanItems = [];
        $totalAmount = 0;

        foreach ($items as $row) {
            $pid  = (int)($row['product_id'] ?? 0);
            $qty  = (float)($row['quantity'] ?? 0);
            $prc  = (float)($row['unit_price'] ?? 0);

            if ($pid <= 0 || $qty <= 0) {
                continue;
            }

            $lineTotal = round($qty * $prc, 3);
            $totalAmount += $lineTotal;

            $cleanItems[] = [
                'product_id'  => $pid,
                'quantity'    => $qty,
                'unit_price'  => $prc,
                'total_price' => $lineTotal
            ];
        }

        if (!count($cleanItems)) {
            json_error('Kamida bitta mahsulot kiritilishi kerak.', 400);
        }

        $pdo->beginTransaction();
        try {
            if ($id > 0) {
                // update header
                $upd = $pdo->prepare("
                    UPDATE sales_orders
                       SET client_id    = :client_id,
                           order_date   = :order_date,
                           status       = :status,
                           total_amount = :total_amount,
                           note         = :note,
                           updated_at   = NOW()
                     WHERE id = :id
                ");
                $upd->execute([
                    ':client_id'    => $client_id,
                    ':order_date'   => $order_date,
                    ':status'       => $status,
                    ':total_amount' => $totalAmount,
                    ':note'         => $note ?: null,
                    ':id'           => $id
                ]);

                // eski itemlarni o‘chirib, qaytadan yozamiz
                $del = $pdo->prepare("DELETE FROM sales_items WHERE order_id = :id");
                $del->execute([':id' => $id]);
                $orderId = $id;
            } else {
                // insert header
                $ins = $pdo->prepare("
                    INSERT INTO sales_orders
                      (client_id, order_date, status, total_amount, note, created_at, created_by)
                    VALUES
                      (:client_id, :order_date, :status, :total_amount, :note, NOW(), :created_by)
                ");
                $ins->execute([
                    ':client_id'    => $client_id,
                    ':order_date'   => $order_date,
                    ':status'       => $status,
                    ':total_amount' => $totalAmount,
                    ':note'         => $note ?: null,
                    ':created_by'   => current_user_id() ?: null
                ]);
                $orderId = (int)$pdo->lastInsertId();
                $id = $orderId;
            }

            // items insert
            $itemIns = $pdo->prepare("
                INSERT INTO sales_items
                  (order_id, product_id, quantity, unit_price, total_price, created_at)
                VALUES
                  (:order_id, :product_id, :quantity, :unit_price, :total_price, NOW())
            ");
            foreach ($cleanItems as $ci) {
                $itemIns->execute([
                    ':order_id'    => $orderId,
                    ':product_id'  => $ci['product_id'],
                    ':quantity'    => $ci['quantity'],
                    ':unit_price'  => $ci['unit_price'],
                    ':total_price' => $ci['total_price'],
                ]);
            }

            $pdo->commit();
            json_ok([
                'message' => $id > 0 ? 'Sotuv saqlandi' : 'Yangi sotuv yaratildi',
                'id'      => $id,
                'total_amount' => $totalAmount
            ]);
        } catch (Throwable $e) {
            $pdo->rollBack();
            json_error('Saqlashda xatolik', 500);
        }
    }

    // === 4) 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');
        }

        $pdo->beginTransaction();
        try {
            $delItems = $pdo->prepare("DELETE FROM sales_items WHERE order_id = :id");
            $delItems->execute([':id' => $id]);

            $delOrder = $pdo->prepare("DELETE FROM sales_orders WHERE id = :id");
            $delOrder->execute([':id' => $id]);

            $pdo->commit();
            json_ok(['message' => 'Sotuv o‘chirildi', 'id' => $id]);
        } catch (Throwable $e) {
            $pdo->rollBack();
            json_error('O‘chirishda xatolik', 500);
        }
    }

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

} catch (Throwable $e) {
    json_error('Server xatosi', 500);
}
