<?php

namespace App\Controllers\API;

use App\Controllers\BaseController;
use App\Models\OrderModel;
use App\Models\OrderDetailModel;
use App\Models\TrackingModel;
use App\Libraries\ResponseFormatter;

class OrderController extends BaseController
{
    protected $orderModel;
    protected $detailModel;
    protected $trackingModel;
    protected $db;

    public function __construct()
    {
        $this->orderModel = new OrderModel();
        $this->detailModel = new OrderDetailModel();
        $this->trackingModel = new TrackingModel();
        $this->db = \Config\Database::connect();
    }

    // 📌 GET ALL ORDER
  public function index()
{
    $page   = (int) ($this->request->getGet('page') ?? 1);
    $limit  = 10;
    $offset = ($page - 1) * $limit;

    $search = $this->request->getGet('search');
    $status = $this->request->getGet('status');

    $builder = $this->orderModel
        ->select("
            orders.*,
            customers.name as customer_name,
            (
                SELECT status 
                FROM order_tracking 
                WHERE order_tracking.order_id = orders.id 
                ORDER BY id DESC 
                LIMIT 1
            ) as last_status
        ")
        ->join('customers', 'customers.id = orders.customer_id');

    // 🔍 SEARCH (invoice + nama)
    if (!empty($search)) {
        $builder->groupStart()
            ->like('orders.invoice_code', $search)
            ->orLike('customers.name', $search)
        ->groupEnd();
    }

    // 🎯 FILTER STATUS (WAJIB pakai WHERE subquery, jangan HAVING)
    if (!empty($status) && $status !== 'all') {
        $builder->where("
            (
                SELECT status 
                FROM order_tracking 
                WHERE order_tracking.order_id = orders.id 
                ORDER BY id DESC 
                LIMIT 1
            ) = '{$status}'
        ");
    }

    // 🔢 TOTAL
    $total = $builder->countAllResults(false);

    // 📦 DATA
    $orders = $builder
        ->orderBy('orders.id', 'DESC')
        ->findAll($limit, $offset);

    return $this->response->setJSON([
        'status' => true,
        'data' => $orders,
        'meta' => [
            'page' => $page,
            'limit' => $limit,
            'total' => $total,
            'has_more' => ($offset + $limit) < $total
        ]
    ]);
}
    // 📌 GET DETAIL ORDER
    public function show($id)
    {
        $order = $this->orderModel->getFullOrder($id);

        $details = $this->detailModel
            ->select('order_details.*, services.name as service_name')
            ->join('services', 'services.id = order_details.service_id')
            ->where('order_id', $id)
            ->findAll();

        $tracking = $this->trackingModel
            ->where('order_id', $id)
            ->orderBy('id', 'ASC')
            ->findAll();

        return $this->response->setJSON(
            ResponseFormatter::success([
                'order' => $order,
                'details' => $details,
                'tracking' => $tracking
            ])
        );
    }

    // 🚀 CREATE ORDER (INTI SISTEM)
    public function create()
{
    $input = $this->request->getJSON(true);

    $this->db->transBegin();
$user = $this->request->user ?? null;
    try {

        $invoice = 'INV-' . date('YmdHis');

        $orderId = $this->orderModel->insert([
            'invoice_code' => $invoice,
            'customer_id' => $input['customer_id'],
             'user_id' => $user->id, // ✅ FIX
            'status' => 'new',
            'payment_status' => 'unpaid',
            'total_price' => 0
        ]);
//dd($this->request->user);
        $total = 0;

        foreach ($input['details'] as $item) {

            // 🔥 ambil harga dari DB
            $service = $this->db->table('services')
                ->where('id', $item['service_id'])
                ->get()
                ->getRow();

            if (!$service) {
                throw new \Exception('Service tidak ditemukan');
            }

            $price = $service->price;
            $subtotal = $item['qty'] * $price;

            $total += $subtotal;

            $this->detailModel->insert([
                'order_id' => $orderId,
                'service_id' => $item['service_id'],
                'qty' => $item['qty'],
                'price' => $price,
                'subtotal' => $subtotal
            ]);
        }

        // update total
        $this->orderModel->update($orderId, [
            'total_price' => $total
        ]);

        // tracking awal
        $this->trackingModel->insert([
            'order_id' => $orderId,
            'status' => 'new',
            'description' => 'Order dibuat'
        ]);

        if ($this->db->transStatus() === false) {
            throw new \Exception('Gagal transaksi');
        }

        $this->db->transCommit();

        return $this->response->setJSON(
            ResponseFormatter::success([
                'order_id' => $orderId,
                'invoice' => $invoice
            ])
        );

    } catch (\Exception $e) {

        $this->db->transRollback();

        return $this->response->setJSON(
            ResponseFormatter::error($e->getMessage())
        );
    }
}

    // 🔄 UPDATE STATUS
    public function updateStatus($id)
{
    $input = $this->request->getJSON(true);

    if (!$input || !isset($input['status'])) {
        return $this->response->setJSON(
            ResponseFormatter::error('Status tidak dikirim')
        );
    }

    $this->orderModel->update($id, [
        'status' => $input['status']
    ]);

    $this->trackingModel->insert([
        'order_id' => $id,
        'status' => $input['status'],
        'description' => $input['description'] ?? ''
    ]);

    return $this->response->setJSON(
        ResponseFormatter::success($input, 'Status updated')
    );
    log_message('error', 'UPDATE HIT ID: ' . $id);
}
}