<?php
namespace App\Controllers;

use App\Models\OrderTrackingModel;
use CodeIgniter\Controller;

class OrderTracking extends BaseController
{
    protected $session;
    protected $trackingModel;

    public function __construct()
    {
        $this->session = session();
        helper(['url', 'form']);

        // Block access if not logged in
        if (!$this->session->get('isLoggedIn')) {
            return redirect()->to(base_url('authController'));
        }

        $this->trackingModel = new OrderTrackingModel();
    }

    // Page to show order tracking with dropdown
    public function index()
    {
        $phone = $this->session->get('phone');

        // Fetch all orders for this phone
        $userOrders = $this->trackingModel->getOrdersByPhone($phone);

        return view('track_order', [
            'customer_name' => $this->session->get('name'), // use in view
            'userOrders'    => $userOrders
        ]);
    }

    // Fetch tracking status by order ID (AJAX)
    public function getStatus($orderId)
    {
        $phone = $this->session->get('phone');

        $data = $this->trackingModel->getTrackingByPhone($orderId, $phone);

        if ($data) {
            return $this->response->setJSON(['success' => true, 'data' => $data]);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'No tracking found for this order']);
        }
    }
}
