<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

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

final class AdminOrgReviewersController extends Controller
{
    public function index(): void
    {
        require_admin_area();
        require_org_context();

        $db=Database::getInstance();
        $orgId=(int)current_org_id();

        $st=$db->prepare("
          SELECT ou.user_id, ou.role_code, u.email, u.first_name, u.last_name
          FROM org_users ou
          JOIN users u ON u.id=ou.user_id
          WHERE ou.org_id=:org AND ou.is_active=1 AND ou.role_code='reviewer'
          ORDER BY u.id DESC
        ");
        $st->execute([':org'=>$orgId]);
        $rows=$st->fetchAll()?:[];

        $this->view('admin/org_reviewers/index',['rows'=>$rows]);
    }

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

        $db=Database::getInstance();
        $orgId=(int)current_org_id();
        $email=trim((string)($_POST['email']??''));

        if($email===''){ header('Location: '.base_path('admin/reviewers')); exit; }

        $st=$db->prepare("SELECT id FROM users WHERE email=:e LIMIT 1");
        $st->execute([':e'=>$email]);
        $uid=(int)($st->fetchColumn()?:0);

        if($uid<=0){
          if(function_exists('flash_set')) flash_set('danger','User not found');
          header('Location: '.base_path('admin/reviewers')); exit;
        }

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

        if(function_exists('flash_set')) flash_set('success','Reviewer added to organization');
        header('Location: '.base_path('admin/reviewers')); exit;
    }

    public function remove(): void
    {
        require_admin_area(); require_org_context();
        $db=Database::getInstance();
        $orgId=(int)current_org_id();
        $uid=(int)($_GET['user_id']??0);

        if($uid>0){
          $db->prepare("UPDATE org_users SET is_active=0 WHERE org_id=:o AND user_id=:u AND role_code='reviewer'")
             ->execute([':o'=>$orgId,':u'=>$uid]);
        }
        header('Location: '.base_path('admin/reviewers')); exit;
    }
}
