<?php
namespace App\Controllers;

use App\Models\DeliveryModel;
use App\Models\DeliveryHistoryModel;
use App\Models\OrderModel;

class DeliveryController extends BaseController
{
    public function index()
    {
        $delivery = new DeliveryModel();
        $data['all'] = $delivery->select('delivery.*, orders.order_no, orders.customer_name')
            ->join('orders', 'orders.id = delivery.order_id')
            ->findAll();

        return view('delivery/index', $data);
    }

    public function view($id)
    {
        $delivery = new DeliveryModel();
        $history = new DeliveryHistoryModel();

        $data['delivery'] = $delivery->select('delivery.*, orders.order_no, orders.customer_name, orders.delivery_address')
            ->join('orders', 'orders.id = delivery.order_id')
            ->where('delivery.id', $id)
            ->first();

        $data['history'] = $history->where('delivery_id', $id)->orderBy('id', 'ASC')->findAll();

        return view('delivery/view', $data);
    }

    public function updateStatus()
    {
        $delivery_id = $this->request->getPost('delivery_id');
        $status = $this->request->getPost('status');
        $message = $this->request->getPost('message');

        $delivery = new DeliveryModel();
        $history = new DeliveryHistoryModel();

        // Update Main Table
        $delivery->update($delivery_id, [
            'current_status' => $status,
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        // Insert History
        $history->insert([
            'delivery_id' => $delivery_id,
            'status' => $status,
            'message' => $message
        ]);

        return redirect()->back()->with('success', 'Delivery Status Updated');
    }
}
