<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

final class ChooseOrgController extends Controller
{
    public function index(): void
    {
        require_login();
        $db = Database::getInstance();
        $uid = (int)auth_id();

        $st = $db->prepare("
          SELECT o.id, o.name, o.code, o.is_active, ou.role_code
          FROM org_users ou
          JOIN organizations o ON o.id=ou.org_id
          WHERE ou.user_id=:u AND ou.is_active=1
          ORDER BY o.name ASC
        ");
        $st->execute([':u'=>$uid]);
        $orgs = $st->fetchAll() ?: [];

        $force = (int)($_GET['force'] ?? 0);

        // auto-select only if single org AND not forced
        if ($force !== 1 && count($orgs) === 1) {
            set_current_org_id((int)$orgs[0]['id']);
            header('Location: ' . base_path('dashboard'));
            exit;
        }

        $this->view('choose_org/index', compact('orgs'));
    }

    public function select(): void
    {
        require_login();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { http_response_code(405); return; }

        $orgId = (int)($_POST['org_id'] ?? 0);
        if ($orgId <= 0) {
            if(function_exists('flash_set')) flash_set('danger','Missing organization');
            header('Location: ' . base_path('choose-org'));
            exit;
        }

        $db = Database::getInstance();
        $uid = (int)auth_id();
        $st = $db->prepare("SELECT COUNT(*) FROM org_users WHERE org_id=:o AND user_id=:u AND is_active=1");
        $st->execute([':o'=>$orgId, ':u'=>$uid]);

        if ((int)$st->fetchColumn() <= 0) {
            if(function_exists('flash_set')) flash_set('danger','Not a member of this organization');
            header('Location: ' . base_path('choose-org'));
            exit;
        }

        set_current_org_id($orgId);
        if(function_exists('flash_set')) flash_set('success','Organization selected');
        header('Location: ' . base_path('dashboard'));
        exit;
    }

    public function clear(): void
    {
        require_login();
        set_current_org_id(0);
        header('Location: ' . base_path('choose-org?force=1'));
        exit;
    }
}
