<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class OwnerController extends Controller
{
    private function requireOwner(): void {

        require_login();

        $isOwner = function_exists('is_owner') && is_owner();
        $isSuper = function_exists('is_super_admin') && is_super_admin();

        if (!$isOwner && !$isSuper) {
            http_response_code(403);
            echo "Forbidden";
            exit;
        }
    }

    public function index(): void
    {
        $this->requireOwner();
        header('Location: ' . base_path('admin/owner/orgs'));
        exit;
    }

    public function orgs(): void
    {
        $this->requireOwner();
        $db = Database::getInstance();

        $orgs = $db->query("
          SELECT o.*,
            (SELECT COUNT(*) FROM conferences c WHERE c.org_id=o.id) AS conferences_count,
            (SELECT COUNT(*) FROM org_users ou WHERE ou.org_id=o.id AND ou.is_active=1) AS members_count
          FROM organizations o
          ORDER BY o.id DESC
        ")->fetchAll() ?: [];

        $admins = $db->query("
          SELECT u.id,u.email,u.first_name,u.last_name
          FROM users u
          ORDER BY u.id DESC
          LIMIT 200
        ")->fetchAll() ?: [];

        $this->view('admin/owner/orgs', compact('orgs','admins'));
    }

    public function orgSave(): void
    {
        $this->requireOwner();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { http_response_code(405); return; }

        $db = Database::getInstance();

        $id = (int)($_POST['id'] ?? 0);
        $name = trim((string)($_POST['name'] ?? ''));
        $code = trim((string)($_POST['code'] ?? ''));
        $email = trim((string)($_POST['contact_email'] ?? ''));

        if ($name === '' || $code === '') {
            if(function_exists('flash_set')) flash_set('danger','Missing name/code');
            header('Location: ' . base_path('admin/owner/orgs'));
            exit;
        }

        if ($id > 0) {
            $db->prepare("UPDATE organizations SET name=:n, code=:c, contact_email=:e WHERE id=:id")
               ->execute([':n'=>$name,':c'=>$code,':e'=>($email!==''?$email:null),':id'=>$id]);
            if(function_exists('flash_set')) flash_set('success','Organization updated');
        } else {
            $db->prepare("INSERT INTO organizations(name,code,contact_email,is_active) VALUES(:n,:c,:e,1)")
               ->execute([':n'=>$name,':c'=>$code,':e'=>($email!==''?$email:null)]);
            if(function_exists('flash_set')) flash_set('success','Organization created');
        }

        header('Location: ' . base_path('admin/owner/orgs'));
        exit;
    }

    public function orgToggle(): void
    {
        $this->requireOwner();
        $db = Database::getInstance();
        $id = (int)($_GET['id'] ?? 0);
        if ($id > 0) {
            $db->prepare("UPDATE organizations SET is_active=IF(is_active=1,0,1) WHERE id=:id")
               ->execute([':id'=>$id]);
            if(function_exists('flash_set')) flash_set('success','Toggled');
        }
        header('Location: ' . base_path('admin/owner/orgs'));
        exit;
    }

    public function assignAdmin(): void
    {
        $this->requireOwner();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { http_response_code(405); return; }

        $db = Database::getInstance();
        $orgId = (int)($_POST['org_id'] ?? 0);
        $userId = (int)($_POST['user_id'] ?? 0);

        if ($orgId<=0 || $userId<=0) {
            if(function_exists('flash_set')) flash_set('danger','Missing org/user');
            header('Location: ' . base_path('admin/owner/orgs'));
            exit;
        }

        $db->prepare("
          INSERT INTO org_users(org_id,user_id,role_code,is_active)
          VALUES(:o,:u,'org_admin',1)
          ON DUPLICATE KEY UPDATE role_code='org_admin', is_active=1
        ")->execute([':o'=>$orgId,':u'=>$userId]);

        if(function_exists('flash_set')) flash_set('success','Org admin assigned');
        header('Location: ' . base_path('admin/owner/orgs'));
        exit;
    }

    public function impersonate(): void
    {
        $this->requireOwner();
        $orgId = (int)($_GET['org_id'] ?? 0);
        if ($orgId > 0 && function_exists('set_current_org_id')) {
            set_current_org_id($orgId);
            AppCoreAudit::log('owner_impersonation','organization', $orgId);
            if(function_exists('flash_set')) flash_set('success','Organization context set');
        }
        header('Location: ' . base_path('admin/submissions'));
        exit;
    }
}
