<?php
declare(strict_types=1);
namespace App\Repositories;

use App\Core\Repository;

final class TailoringRepository extends Repository {
    public function searchOrders(string $q = ''): array {
        $params = [];
        $where = '';
        if ($q !== '') {
            $where = "WHERE (t.ticket_no LIKE ? OR c.phone LIKE ? OR c.full_name LIKE ?)";
            $like = '%' . $q . '%';
            $params = [$like, $like, $like];
        }
        return $this->all(
            "SELECT t.*, c.full_name, c.phone, u.full_name AS created_by_name
             FROM tailoring_orders t
             JOIN customers c ON c.id = t.customer_id
             LEFT JOIN users u ON u.id = t.created_by
             $where
             ORDER BY t.id DESC",
            $params
        );
    }

    public function createOrder(int $customerId, int $qty, int $createdBy): int {
        $price = (float)(new SettingRepository())->get('tailoring_unit_price', '0.000');
        $year = date('Y');
        $next = (int)($this->one("SELECT COUNT(*) c FROM tailoring_orders WHERE YEAR(created_at)=YEAR(CURDATE())")['c'] ?? 0) + 1;
        $ticketNo = 'T-' . $year . '-' . str_pad((string)$next, 5, '0', STR_PAD_LEFT);
        $total = $price * $qty;

        $this->db->beginTransaction();
        try {
            $orderId = $this->insert(
                "INSERT INTO tailoring_orders(ticket_no, customer_id, qty, unit_price, total_amount, status, created_by, created_at, updated_at)
                 VALUES(?,?,?,?,?,'pending',?,NOW(),NOW())",
                [$ticketNo, $customerId, $qty, number_format($price,3,'.',''), number_format($total,3,'.',''), $createdBy]
            );

            for ($i = 1; $i <= $qty; $i++) {
                $barcodeNo = $ticketNo . '-' . str_pad((string)$i, 2, '0', STR_PAD_LEFT);
                $this->insert(
                    "INSERT INTO tailoring_order_barcodes(tailoring_order_id, barcode_no, status, created_at, updated_at)
                     VALUES(?,?,'pending',NOW(),NOW())",
                    [$orderId, $barcodeNo]
                );
            }
            $this->db->commit();
            return $orderId;
        } catch (\Throwable $e) {
            $this->db->rollBack();
            throw $e;
        }
    }

    public function findOrder(int $id): ?array {
        return $this->one(
            "SELECT t.*, c.full_name, c.phone
             FROM tailoring_orders t
             JOIN customers c ON c.id = t.customer_id
             WHERE t.id=? LIMIT 1",
            [$id]
        );
    }

    public function orderBarcodes(int $orderId): array {
        return $this->all("SELECT * FROM tailoring_order_barcodes WHERE tailoring_order_id=? ORDER BY id ASC", [$orderId]);
    }

    public function markReady(int $id, int $userId): ?array {
        $order = $this->findOrder($id);
        if (!$order) return null;

        $this->db->beginTransaction();
        try {
            $this->exec("UPDATE tailoring_orders SET status='ready', ready_by=?, ready_at=NOW(), updated_at=NOW() WHERE id=?", [$userId, $id]);
            $this->exec("UPDATE tailoring_order_barcodes SET status='ready', updated_at=NOW() WHERE tailoring_order_id=?", [$id]);
            $this->db->commit();
        } catch (\Throwable $e) {
            $this->db->rollBack();
            throw $e;
        }
        return $this->findOrder($id);
    }
}
