<?php
namespace App\Controllers;

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

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

use App\Core\Database;
use App\Core\BusinessPermission;

class AdminCommitteeMediaController
{
    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function db()
    {
        return Database::getInstance();
    }

    private function role(): string
    {
        return (string)($_SESSION['role'] ?? $_SESSION['user_role'] ?? '');
    }

    private function requireAccess(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        if (empty($_SESSION['conference_id'])) {
            header("Location: /easychair/select-conference");
            exit;
        }

        if (!in_array($this->role(), ['superadmin','org_admin','admin','organizer','conference_chair'], true)) {
            http_response_code(403);
            exit("Access denied.");
        }
    }

    private function conference(): array
    {
        $stmt = $this->db()->prepare("SELECT * FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([(int)$_SESSION['conference_id']]);
        $c = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$c) {
            exit("Conference not found.");
        }

        if (!ec_is_superadmin() && (int)$c['org_id'] !== (int)($_SESSION['org_id'] ?? 0)) {
            http_response_code(403);
            exit("Invalid organization conference access.");
        }

        return $c;
    }

    private function saveImage(array $conference, string $inputName = 'image'): ?string
    {
        if (empty($_FILES[$inputName]['name']) || !is_uploaded_file($_FILES[$inputName]['tmp_name'])) {
            return null;
        }

        $allowed = ['jpg','jpeg','png','webp'];
        $ext = strtolower(pathinfo($_FILES[$inputName]['name'], PATHINFO_EXTENSION));
        $ext = preg_replace('/[^a-z0-9]/', '', $ext);

        if (!in_array($ext, $allowed, true)) {
            exit("Invalid image type. Allowed: jpg, jpeg, png, webp.");
        }

        $dir = BASE_PATH . '/public/storage/committees/' . (int)$conference['id'];

        if (!is_dir($dir)) {
            mkdir($dir, 0775, true);
        }

        $file = 'committee_' . date('YmdHis') . '_' . rand(1000, 9999) . '.' . $ext;

        if (!move_uploaded_file($_FILES[$inputName]['tmp_name'], $dir . '/' . $file)) {
            exit("Could not upload image.");
        }

        return 'committees/' . (int)$conference['id'] . '/' . $file;
    }

    public function index()
    {

        // Pack512: non-superadmin bypasses selector safely.
        if (function_exists('ec_scope_role') && ec_scope_role() !== 'superadmin') {
            if (function_exists('ec_scope_auto_select_conference')) {
                // ec_scope_auto_select_conference(true);
            }
            $landing = function_exists('ec_scope_landing_url') ? ec_scope_landing_url() : '/easychair/admin/dashboard';
            header("Location: " . $landing);
            exit;
        }

$this->requireAccess();
        BusinessPermission::requirePermission('business.committees.view');

        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            SELECT *
            FROM conference_committees
            WHERE conference_id = ?
              AND org_id = ?
            ORDER BY committee_type, sort_order, id DESC
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $members = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        ob_start();
        require BASE_PATH . '/app/views/admin/committee_media/index.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }

    public function store()
    {
$this->requireAccess();
        BusinessPermission::requireCrud('committees', 'create');

        $conference = $this->conference();

        $type = strtolower(trim($_POST['committee_type'] ?? 'other'));
        $allowed = ['chair','co_chair','editor','section_editor','patron','keynote','tpc','reviewer','panel','organizing','scientific','steering','sponsor','other'];

        if (!in_array($type, $allowed, true)) {
            $type = 'other';
        }

        $imagePath = $this->saveImage($conference, 'image');

        $stmt = $this->db()->prepare("
            INSERT INTO conference_committees
            (org_id, conference_id, committee_type, full_name_ar, full_name_en, title_ar, title_en,
             affiliation_ar, affiliation_en, email, image_path, bio_ar, bio_en, sort_order, is_active, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
        ");

        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $type,
            trim($_POST['full_name_ar'] ?? ''),
            trim($_POST['full_name_en'] ?? ''),
            trim($_POST['title_ar'] ?? ''),
            trim($_POST['title_en'] ?? ''),
            trim($_POST['affiliation_ar'] ?? ''),
            trim($_POST['affiliation_en'] ?? ''),
            trim($_POST['email'] ?? ''),
            $imagePath,
            trim($_POST['bio_ar'] ?? ''),
            trim($_POST['bio_en'] ?? ''),
            (int)($_POST['sort_order'] ?? 1),
            (int)$_SESSION['user_id']
        ]);

        header("Location: /easychair/admin/committee-media");
        exit;
    }

    public function update()
    {
        $this->requireAccess();
        BusinessPermission::requireCrud('committees', 'update');

        $conference = $this->conference();
        $id = (int)($_POST['id'] ?? 0);

        $type = strtolower(trim($_POST['committee_type'] ?? 'other'));
        $allowed = ['chair','co_chair','editor','section_editor','patron','keynote','tpc','reviewer','panel','organizing','scientific','steering','sponsor','other'];

        if (!in_array($type, $allowed, true)) {
            $type = 'other';
        }

        $imagePath = $this->saveImage($conference, 'image');

        if ($imagePath) {
            $stmt = $this->db()->prepare("
                UPDATE conference_committees
                SET committee_type=?,
                    full_name_ar=?,
                    full_name_en=?,
                    title_ar=?,
                    title_en=?,
                    affiliation_ar=?,
                    affiliation_en=?,
                    email=?,
                    image_path=?,
                    bio_ar=?,
                    bio_en=?,
                    sort_order=?,
                    updated_at=NOW()
                WHERE id=?
                  AND conference_id=?
                  AND org_id=?
            ");
            $stmt->execute([
                $type,
                trim($_POST['full_name_ar'] ?? ''),
                trim($_POST['full_name_en'] ?? ''),
                trim($_POST['title_ar'] ?? ''),
                trim($_POST['title_en'] ?? ''),
                trim($_POST['affiliation_ar'] ?? ''),
                trim($_POST['affiliation_en'] ?? ''),
                trim($_POST['email'] ?? ''),
                $imagePath,
                trim($_POST['bio_ar'] ?? ''),
                trim($_POST['bio_en'] ?? ''),
                (int)($_POST['sort_order'] ?? 1),
                $id,
                (int)$conference['id'],
                (int)$conference['org_id']
            ]);
        } else {
            $stmt = $this->db()->prepare("
                UPDATE conference_committees
                SET committee_type=?,
                    full_name_ar=?,
                    full_name_en=?,
                    title_ar=?,
                    title_en=?,
                    affiliation_ar=?,
                    affiliation_en=?,
                    email=?,
                    bio_ar=?,
                    bio_en=?,
                    sort_order=?,
                    updated_at=NOW()
                WHERE id=?
                  AND conference_id=?
                  AND org_id=?
            ");
            $stmt->execute([
                $type,
                trim($_POST['full_name_ar'] ?? ''),
                trim($_POST['full_name_en'] ?? ''),
                trim($_POST['title_ar'] ?? ''),
                trim($_POST['title_en'] ?? ''),
                trim($_POST['affiliation_ar'] ?? ''),
                trim($_POST['affiliation_en'] ?? ''),
                trim($_POST['email'] ?? ''),
                trim($_POST['bio_ar'] ?? ''),
                trim($_POST['bio_en'] ?? ''),
                (int)($_POST['sort_order'] ?? 1),
                $id,
                (int)$conference['id'],
                (int)$conference['org_id']
            ]);
        }

        header("Location: /easychair/admin/committee-media");
        exit;
    }

    public function toggle()
    {
        $this->requireAccess();
        BusinessPermission::requireCrud('committees', 'update');

        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            UPDATE conference_committees
            SET is_active = IF(is_active=1,0,1)
            WHERE id=?
              AND conference_id=?
              AND org_id=?
        ");
        $stmt->execute([(int)($_GET['id'] ?? 0), (int)$conference['id'], (int)$conference['org_id']]);

        header("Location: /easychair/admin/committee-media");
        exit;
    }

    public function delete()
    {
        $this->requireAccess();
        BusinessPermission::requireCrud('committees', 'delete');

        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            DELETE FROM conference_committees
            WHERE id=?
              AND conference_id=?
              AND org_id=?
        ");
        $stmt->execute([(int)($_GET['id'] ?? 0), (int)$conference['id'], (int)$conference['org_id']]);

        header("Location: /easychair/admin/committee-media");
        exit;
    }

    public function cleanupEmpty()
    {
        $this->requireAccess();
        BusinessPermission::requireCrud('committees', 'delete');

        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            DELETE FROM conference_committees
            WHERE conference_id=?
              AND org_id=?
              AND (full_name_ar IS NULL OR TRIM(full_name_ar)='')
              AND (full_name_en IS NULL OR TRIM(full_name_en)='')
              AND (email IS NULL OR TRIM(email)='')
              AND (image_path IS NULL OR TRIM(image_path)='')
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);

        header("Location: /easychair/admin/committee-media");
        exit;
    }
}
