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

/**
 * Saas — SUPER-ADMIN (root, bina tenant slug ke)
 *
 * Root (clinic.munshiji.pk/) => ye controller:
 *   - login (saas_admins)  -> master DB `munshiji_saas`
 *   - dashboard: saas_clinics ki list + per-clinic data stats
 *
 * Tenant URLs (/ammarah, /alkhidmat) iske NIHAI in—wo clinic app hai.
 */
class Saas extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');

        // Super-admin sirf ROOT (bina slug) pe chalta hai. Tenant slug ke
        // sath (/ammarah/saas/login) aane par asal ROOT pe bhej do —
        // warna master tables clinic DB mein dhoondne lagta hai.
        if (method_exists($this->router, 'get_tenant_slug') && $this->router->get_tenant_slug() !== '') {
            $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
            $host   = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
            redirect($scheme . '://' . $host . '/', 'refresh');
        }
    }

    // Root '/'
    public function index()
    {
        if (empty($_SESSION['saas_admin'])) {
            $data['error'] = null;
            $this->load->view('saas/login', $data);
            return;
        }
        $this->dashboard();
    }

    // POST -> /saas/login
    public function login()
    {
        if ($this->input->post()) {
            $login    = trim((string)$this->input->post('username'));
            $password = (string)$this->input->post('password');

            try {
                $admin = $this->db->where('username', $login)
                                  ->or_where('email', $login)
                                  ->get('saas_admins')
                                  ->row();

                if ($admin && password_verify($password, $admin->password)) {
                    $this->session->set_userdata(array(
                        'saas_admin'      => (int)$admin->id,
                        'saas_admin_name'  => $admin->name
                    ));
                    redirect('/');
                    return;
                }
            } catch (Exception $e) {
                // saas_admins table nahi hai -> user ko guide dikhao
            }
            $data['error'] = 'Invalid credentials, ya master DB setup nahi hua (sql/003 chalao)';
            $this->load->view('saas/login', $data);
            return;
        }
        redirect('/');
    }

    public function logout()
    {
        $this->session->unset_userdata('saas_admin');
        $this->session->unset_userdata('saas_admin_name');
        redirect('/');
    }

    protected function dashboard()
    {
        $clinics = array();
        $db_error = null;

        try {
            $clinics = $this->db->order_by('id', 'ASC')->get('saas_clinics')->result();
        } catch (Exception $e) {
            $db_error = $e->getMessage();
        }

        if ($db_error !== null) {
            $this->load->view('saas/error', array('message' => $db_error));
            return;
        }

        // Har clinic ke liye best-effort data stats (uski apni DB se)
        foreach ($clinics as $c) {
            $c->stats = $this->clinic_stats($c->db_name);
        }

        $data['clinics']  = $clinics;
        $data['saas_name'] = isset($_SESSION['saas_admin_name']) ? $_SESSION['saas_admin_name'] : '';
        $this->load->view('saas/dashboard', $data);
    }

    /**
     * Kisi clinic ke DB se row counts — best effort (agar DB exist na ho to 'pending' batati hai).
     */
    private function clinic_stats($db_name)
    {
        $out = array('status' => 'ok', 'counts' => array());
        try {
            $host = $this->db->hostname;
            $user = $this->db->username;
            $pass = $this->db->password;

            $pdo = new PDO(
                'mysql:host=' . $host . ';dbname=' . $db_name . ';charset=utf8',
                $user, $pass,
                array(PDO::ATTR_TIMEOUT => 4, PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT)
            );

            $tables = array('tokens' => 'kns1_tokens', 'users' => 'kns1_users',
                            'staff' => 'kns1_staff', 'payments' => 'kns1_payment',
                            'expenses' => 'kns1_expenses');

            // kns1_ prefix config se bhi ho sakta hai; yahan static rakha hai
            foreach ($tables as $label => $table) {
                $st = @$pdo->query('SELECT COUNT(*) c FROM `' . $table . '`');
                $out['counts'][$label] = $st ? (int)$st->fetchColumn() : 0;
            }
            $pdo = null;
        } catch (Exception $e) {
            $out['status'] = 'unprovisioned';
            $out['error']  = $e->getMessage();
        }
        return $out;
    }
}