<?php

namespace App\Controllers;

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

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

class AdminConferencesController extends Controller
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    /*
    --------------------------------------------------
    Permissions (FIXED)
    --------------------------------------------------
    */

    private function requireAdmin()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

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

        if (!in_array(
            $_SESSION['role'] ?? '',
            ['superadmin','admin','org_admin']
        )) {
            die("Access denied.");
        }
    }

    /*
    --------------------------------------------------
    List (FIXED for view)
    --------------------------------------------------
    */

    public function index()
    {
        $this->requireAdmin();

        $stmt = $this->db->query("
            SELECT *
            FROM conferences
            ORDER BY id DESC
        ");

        $conferences =
            $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $this->render(
            'admin/conferences/index',
            compact('conferences')
        );
    }

    /*
    --------------------------------------------------
    Create (SUPERADMIN ENABLED)
    --------------------------------------------------
    */

public function create()
{
    $this->requireAdmin();

    /*
    Load organizations
    */

    $stmt = $this->db->query("
        SELECT id, name
        FROM organizations
        ORDER BY name ASC
    ");

    $organizations =
        $stmt->fetchAll(\PDO::FETCH_ASSOC);

    $this->render(
        'admin/conferences/form',
        [
            'mode' => 'create',
            'row'  => [],
            'organizations' => $organizations
        ]
    );
}    


    /*
    --------------------------------------------------
    Store
    --------------------------------------------------
    */

public function store()
{
    $this->requireAdmin();

    $title_en = trim($_POST['title_en'] ?? '');
    $title_ar = trim($_POST['title_ar'] ?? '');

    if (!$title_en || !$title_ar) {
        die("Both Arabic and English titles are required");
    }

    /*
    Generate slug
    */

    $baseSlug = strtolower(
        preg_replace('/[^a-zA-Z0-9]+/', '-', $title_en)
    );

    $slug = trim($baseSlug, '-');

    if (!$slug) {
        $slug = 'conference';
    }

    $original = $slug;
    $i = 1;

    while (true) {

        $stmt = $this->db->prepare("
            SELECT id FROM conferences WHERE slug = ?
        ");

        $stmt->execute([$slug]);

        if (!$stmt->fetch()) break;

        $slug = $original . '-' . $i++;
    }

    /*
    Short name (REQUIRED FIELD)
    */

    $short_name = strtoupper(substr($slug, 0, 10));

    /*
    Org fallback
    */

    $org_id = (int)($_POST['org_id'] ?? 0);

if (!$org_id) {
    die("Organization is required");
}

    if (!$org_id) {

        $stmt = $this->db->query("
            SELECT id FROM organizations LIMIT 1
        ");

        $org_id = (int)$stmt->fetchColumn();

        $_SESSION['org_id'] = $org_id;
    }

    /*
    Insert
    */

    $stmt = $this->db->prepare("
        INSERT INTO conferences
        (
            org_id,
            slug,
            short_name,
            title_en,
            title_ar,
            status,
            created_at
        )
        VALUES
        (?, ?, ?, ?, ?, 'draft', NOW())
    ");

    $stmt->execute([
        $org_id,
        $slug,
        $short_name,
        $title_en,
        $title_ar
    ]);

    header("Location: /easychair/admin/conferences");
    exit;
}    

public function editHomepage()
{
    $id = (int)($_GET['id'] ?? 0);

    $stmt = $this->db->prepare("
        SELECT * FROM conferences WHERE id=?
    ");
    $stmt->execute([$id]);

    $conference = $stmt->fetch(\PDO::FETCH_ASSOC);

    require BASE_PATH . '/app/views/admin/conferences/homepage.php';
}

public function saveHomepage()
{
    $stmt = $this->db->prepare("
        UPDATE conferences
        SET
            homepage_title = ?,
            homepage_description = ?,
            homepage_about = ?,
            homepage_dates = ?
        WHERE id = ?
    ");

    $stmt->execute([
        $_POST['homepage_title'],
        $_POST['homepage_description'],
        $_POST['homepage_about'],
        $_POST['homepage_dates'],
        $_POST['id']
    ]);

    header("Location: /easychair/admin/conferences");
}

}
