<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\SuperAuth;
use App\Models\Tenant;
use Core\Controller;
use Core\DB;
use Core\Session;
use Core\Tool;

final class SuperAdminController extends Controller
{
    public function middleware(): array
    {
        return [SuperAuth::class];
    }

    public function index(): void
    {
        $tenants = DB::all(
            'SELECT * FROM tenants WHERE deleted_at IS NULL ORDER BY created_at DESC'
        );

        $defaultChecklists = DB::all(
            'SELECT dc.*, at.name AS asset_type_name
               FROM default_checklists dc
          LEFT JOIN asset_types at ON at.asset_type_id = dc.asset_type_id
              WHERE dc.deleted_at IS NULL
              ORDER BY dc.name'
        );

        $this->render('super-admin/index', [
            'tenants'            => $tenants,
            'defaultChecklists'  => $defaultChecklists,
            'impersonatedId'     => $_SESSION['impersonated_tenant_id'] ?? null,
            'impersonatedName'   => $_SESSION['impersonated_tenant_name'] ?? null,
            'flash'              => Session::flash('super_msg'),
            'error'              => Session::flash('super_error'),
        ]);
    }

    // ── Tenant CRUD ──────────────────────────────────────────────────

    public function createTenant(): void
    {
        $this->render('super-admin/tenant-form', [
            'tenant' => null,
            'csrf'   => Tool::generateCsrf(),
        ]);
    }

    public function editTenant(int $id): void
    {
        $tenant = Tenant::findById($id);
        if (!$tenant) { Session::flash('super_error', 'Tenant not found.'); redirect('/SuperAdmin'); }
        $this->render('super-admin/tenant-form', [
            'tenant' => $tenant,
            'csrf'   => Tool::generateCsrf(),
        ]);
    }

    public function saveTenant(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/SuperAdmin');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('super_error', 'Session expired.'); redirect('/SuperAdmin');
        }

        $id   = (int) ($_POST['tenant_id'] ?? 0);
        $name = trim((string) ($_POST['name'] ?? ''));
        $sub  = trim((string) ($_POST['subdomain'] ?? ''));
        $status = in_array($_POST['status'] ?? '', ['active', 'inactive', 'suspended'], true)
            ? $_POST['status'] : 'active';

        if ($name === '') {
            Session::flash('super_error', 'Tenant name is required.');
            redirect($id > 0 ? "/SuperAdmin/editTenant/{$id}" : '/SuperAdmin/createTenant');
        }

        $superId = (int) (Session::user()['user_id'] ?? 0);

        if ($id > 0) {
            DB::run(
                'UPDATE tenants SET name = :n, subdomain = :s, status = :st, updated_at = NOW()
                  WHERE tenant_id = :id',
                ['n' => $name, 's' => $sub ?: null, 'st' => $status, 'id' => $id]
            );
            Session::flash('super_msg', 'Tenant updated.');
        } else {
            DB::insert('tenants', [
                'name'             => $name,
                'subdomain'        => $sub ?: null,
                'status'           => $status,
                'created_by_super' => $superId,
            ]);
            Session::flash('super_msg', 'Tenant created. Default checklists will be cloned.');
        }
        redirect('/SuperAdmin');
    }

    public function toggleStatus(int $id): void
    {
        $tenant = Tenant::findById($id);
        if (!$tenant) { Session::flash('super_error', 'Tenant not found.'); redirect('/SuperAdmin'); }
        $newStatus = $tenant['status'] === 'active' ? 'suspended' : 'active';
        DB::run('UPDATE tenants SET status = :st WHERE tenant_id = :id', ['st' => $newStatus, 'id' => $id]);
        Session::flash('super_msg', "Tenant {$tenant['name']} is now {$newStatus}.");
        redirect('/SuperAdmin');
    }

    // ── Impersonation ────────────────────────────────────────────────

    public function impersonate(int $id): void
    {
        $tenant = Tenant::findById($id);
        if (!$tenant) { Session::flash('super_error', 'Tenant not found.'); redirect('/SuperAdmin'); }

        $_SESSION['impersonated_tenant_id']   = $id;
        $_SESSION['impersonated_tenant_name'] = $tenant['name'];
        $_SESSION['tenant_id']                = $id;

        Session::flash('super_msg', "Now viewing as: {$tenant['name']}");
        redirect('/Home');
    }

    public function endImpersonation(): void
    {
        unset($_SESSION['impersonated_tenant_id'], $_SESSION['impersonated_tenant_name'], $_SESSION['tenant_id']);
        Session::flash('super_msg', 'Returned to SuperAdmin view.');
        redirect('/SuperAdmin');
    }

    // ── Default Checklists ───────────────────────────────────────────

    public function defaultChecklists(): void
    {
        $list = DB::all(
            "SELECT dc.*, at.name AS asset_type_name,
                    (SELECT COUNT(*) FROM default_checklist_tasks t WHERE t.default_checklist_id = dc.default_checklist_id) AS task_count
               FROM default_checklists dc
          LEFT JOIN asset_types at ON at.asset_type_id = dc.asset_type_id
              WHERE dc.deleted_at IS NULL
              ORDER BY dc.name"
        );
        $this->render('super-admin/checklists', [
            'checklists' => $list,
            'flash'      => Session::flash('super_msg'),
            'csrf'       => Tool::generateCsrf(),
        ]);
    }

    public function createChecklist(): void
    {
        $this->render('super-admin/checklist-form', [
            'checklist' => null,
            'csrf'      => Tool::generateCsrf(),
        ]);
    }

    public function editChecklist(int $id): void
    {
        $cl = DB::one('SELECT * FROM default_checklists WHERE default_checklist_id = :id AND deleted_at IS NULL', ['id' => $id]);
        if (!$cl) { Session::flash('super_error', 'Checklist not found.'); redirect('/SuperAdmin/defaultChecklists'); }
        $tasks = DB::all('SELECT * FROM default_checklist_tasks WHERE default_checklist_id = :id ORDER BY sort_order, task_id', ['id' => $id]);
        $this->render('super-admin/checklist-form', [
            'checklist' => $cl,
            'tasks'     => $tasks,
            'csrf'      => Tool::generateCsrf(),
        ]);
    }

    public function saveChecklist(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/SuperAdmin/defaultChecklists');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('super_error', 'Session expired.'); redirect('/SuperAdmin/defaultChecklists');
        }
        $id   = (int) ($_POST['default_checklist_id'] ?? 0);
        $name = trim((string) ($_POST['name'] ?? ''));
        if ($name === '') { Session::flash('super_error', 'Name is required.'); redirect('/SuperAdmin/defaultChecklists'); }
        $superId = (int) (Session::user()['user_id'] ?? 0);
        $data = [
            'name'              => $name,
            'description'       => $_POST['description'] ?: null,
            'interval_days'     => (int) ($_POST['interval_days'] ?? 30),
            'meter_name'        => $_POST['meter_name'] ?: null,
            'meter_interval'    => $_POST['meter_interval'] ? (int) $_POST['meter_interval'] : null,
            'estimated_minutes' => (int) ($_POST['estimated_minutes'] ?? 60),
            'is_active'         => !empty($_POST['is_active']) ? 1 : 0,
            'updated_at'        => date('Y-m-d H:i:s'),
        ];

        if ($id > 0) {
            DB::run(
                'UPDATE default_checklists SET name=:n, description=:d, interval_days=:i, meter_name=:mn,
                    meter_interval=:mi, estimated_minutes=:e, is_active=:a, updated_at=:u
                 WHERE default_checklist_id = :id',
                array_merge($data, ['id' => $id])
            );
        } else {
            $data['created_by'] = $superId;
            $data['created_at'] = date('Y-m-d H:i:s');
            $id = (int) DB::insert('default_checklists', $data);
        }
        Session::flash('super_msg', 'Checklist saved.');
        redirect("/SuperAdmin/editChecklist/{$id}");
    }

    public function saveTask(int $checklistId): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect("/SuperAdmin/editChecklist/{$checklistId}");
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect("/SuperAdmin/editChecklist/{$checklistId}");
        DB::insert('default_checklist_tasks', [
            'default_checklist_id' => $checklistId,
            'sort_order'           => (int) ($_POST['sort_order'] ?? 0),
            'title'                => trim((string) ($_POST['title'] ?? '')),
            'description'          => $_POST['description'] ?: null,
            'input_type'           => $_POST['input_type'] ?? 'checkbox',
            'is_required'          => !empty($_POST['is_required']) ? 1 : 0,
            'photo_requirement'    => $_POST['photo_requirement'] ?? 'n_a',
        ]);
        Session::flash('super_msg', 'Task added.');
        redirect("/SuperAdmin/editChecklist/{$checklistId}");
    }

    public function deleteTask(int $taskId): void
    {
        $t = DB::one('SELECT default_checklist_id FROM default_checklist_tasks WHERE task_id = :id', ['id' => $taskId]);
        $cid = $t['default_checklist_id'] ?? 0;
        DB::run('DELETE FROM default_checklist_tasks WHERE task_id = :id', ['id' => $taskId]);
        Session::flash('super_msg', 'Task removed.');
        redirect($cid > 0 ? "/SuperAdmin/editChecklist/{$cid}" : '/SuperAdmin/defaultChecklists');
    }

    public function deleteChecklist(int $id): void
    {
        DB::run('UPDATE default_checklists SET deleted_at = NOW() WHERE default_checklist_id = :id', ['id' => $id]);
        Session::flash('super_msg', 'Checklist deleted.');
        redirect('/SuperAdmin/defaultChecklists');
    }

    /**
     * Clone all active default checklists (with their tasks) into a tenant's
     * pm_templates / pm_template_tasks tables.
     */
    public function cloneToTenant(int $tenantId): void
    {
        $tenant = Tenant::findById($tenantId);
        if (!$tenant) { Session::flash('super_error', 'Tenant not found.'); redirect('/SuperAdmin'); }
        $superId = (int) (Session::user()['user_id'] ?? 0);

        $defaults = DB::all(
            'SELECT * FROM default_checklists WHERE deleted_at IS NULL AND is_active = 1'
        );

        $count = 0;
        foreach ($defaults as $dc) {
            $tplId = (int) DB::insert('pm_templates', [
                'tenant_id'         => $tenantId,
                'name'              => $dc['name'],
                'description'       => $dc['description'],
                'asset_type_id'     => $dc['asset_type_id'],
                'interval_days'     => $dc['interval_days'],
                'meter_name'        => $dc['meter_name'],
                'meter_interval'    => $dc['meter_interval'],
                'estimated_minutes' => $dc['estimated_minutes'],
                'is_active'         => $dc['is_active'],
                'created_by'        => $superId,
            ]);

            $tasks = DB::all(
                'SELECT * FROM default_checklist_tasks WHERE default_checklist_id = :id ORDER BY sort_order, task_id',
                ['id' => $dc['default_checklist_id']]
            );
            foreach ($tasks as $t) {
                DB::insert('pm_template_tasks', [
                    'template_id'       => $tplId,
                    'sort_order'        => $t['sort_order'],
                    'title'             => $t['title'],
                    'description'       => $t['description'],
                    'input_type'        => $t['input_type'],
                    'options_json'      => $t['options_json'],
                    'is_required'       => $t['is_required'],
                    'photo_requirement' => $t['photo_requirement'],
                ]);
            }
            $count++;
        }

        Session::flash('super_msg', "{$count} default checklists cloned to {$tenant['name']}.");
        redirect('/SuperAdmin');
    }
}