<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * ---------------------------------------------------------------------------
 * MY_Router  — Multi-tenant foundation (Phase 1)
 * ---------------------------------------------------------------------------
 * Path-based tenants: `clinic.munshiji.pk/ammarah/admin/tokens`
 *        ^^^^^^^^^^^
 * First URI segment = clinic slug. Ye router usay strip karke baaqi path ko
 * normally route karta hai (jaise `/admin/tokens`).
 *
 * Non-breaking: agar first segment kisi registered slug se match na ho (jaise
 * local dev par `admin`), to router exactly pehle jaisa hi behave karta hai.
 */
class MY_Router extends CI_Router {

    public $tenant_slug = '';

    public function _set_request($segments = array())
    {
        if (!empty($segments))
        {
            $tenant_map = file_exists(APPPATH . 'config/tenant.php')
                ? require APPPATH . 'config/tenant.php'
                : array();

            if (is_array($tenant_map) && isset($tenant_map[$segments[0]]))
            {
                $this->tenant_slug = array_shift($segments);
            }
        }

        // Tenant site ka bare root (/ammarah/) => us clinic ka login (/ammarah/admin)
        if ($this->tenant_slug !== '' && count($segments) === 0)
        {
            $segments = array('admin', 'home');
        }

        // Controller DIRECTORY ka bare path (e.g. /admin yani /ammarah/admin)
        // bina method ke CI default-controller kholta hai; hum <dir>/home likh dete.
        if (count($segments) === 1
            && is_dir(APPPATH . 'controllers/' . $segments[0])
            && file_exists(APPPATH . 'controllers/' . $segments[0] . '/home.php'))
        {
            $segments[] = 'home';
        }

        parent::_set_request($segments);
    }

    public function get_tenant_slug()
    {
        return $this->tenant_slug;
    }
}