<?php
namespace App\Controllers;

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

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

use App\Core\Database;

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

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

    private function role(): string
{
    $role =
        strtolower(
            trim(
                (string)(
                    $_SESSION['role']
                    ?? $_SESSION['user_role']
                    ?? ''
                )
            )
        );

    /*
     * Normalize all legacy variants
     */
    if (
        in_array(
            $role,
            [
                'superadmin',
                'super admin',
                'superadmin'
            ],
            true
        )
    ) {
        return 'superadmin';
    }

    return $role;
}

private function requireSuperAdmin()
{
    $role =
        strtolower(
            trim(
                (string)(
                    $_SESSION['role']
                    ?? $_SESSION['user_role']
                    ?? ''
                )
            )
        );

    if (
        !in_array(
            $role,
            [
                'superadmin',
                'super_admin',
                'super admin'
            ],
            true
        )
    ) {

        http_response_code(403);

        die('Access denied.');
    }
}
    private function requireAccess(): void
    {
        $this->startSession();

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

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

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

    private function tableExists(string $table): bool
    {
        try {
            $stmt = $this->db()->prepare("SHOW TABLES LIKE ?");
            $stmt->execute([$table]);
            return (bool)$stmt->fetchColumn();
        } catch (\Throwable $e) {
            return false;
        }
    }

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

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

        if ($this->role() !== 'superadmin') {
            if ((int)$conference['org_id'] !== (int)($_SESSION['org_id'] ?? 0)) {
                http_response_code(403);
                exit("Invalid organization conference access.");
            }
        }

        return $conference;
    }

    private function rows(string $sql, array $params = []): array
    {
        try {
            $stmt = $this->db()->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
        } catch (\Throwable $e) {
            return [];
        }
    }

    private function one(string $sql, array $params = []): ?array
    {
        try {
            $stmt = $this->db()->prepare($sql);
            $stmt->execute($params);
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
            return $row ?: null;
        } catch (\Throwable $e) {
            return null;
        }
    }

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

   // if (
   //     $this->role() === 'superadmin'
    //) {

      //  return $this->sections();
    //}
        $this->requireAccess();
	return $this->sections();

        $conference = $this->conference();
        $cid = (int)$conference['id'];
        $orgId = (int)$conference['org_id'];

        $policy = $this->one("
            SELECT *
            FROM org_conference_policy
            WHERE org_id = ?
            LIMIT 1
        ", [$orgId]);

        $orgConferences = $this->rows("
            SELECT *
            FROM conferences
            WHERE org_id = ?
            ORDER BY id DESC
        ", [$orgId]);

        $blocks = $this->rows("
           SELECT *
    FROM conference_homepage_blocks
    WHERE conference_id = ?
    ORDER BY sort_order ASC, id DESC
", [$cid]);

        /*
        ---------------------------------------------------------
        HOMEPAGE SECTIONS GOVERNANCE
        ---------------------------------------------------------
        */

        $sections = $this->rows("
            SELECT *
            FROM conference_home_sections
            WHERE conference_id = ?
            ORDER BY
                sort_order ASC,
                id ASC
        ", [$cid]);

        $committees = $this->rows("
            SELECT *
            FROM conference_committees
            WHERE conference_id = ?
              AND (org_id = ? OR org_id IS NULL)
            ORDER BY committee_type ASC, sort_order ASC, id DESC
        ", [$cid, $orgId]);

        $templates = $this->rows("
            SELECT *
            FROM conference_email_templates
            WHERE conference_id = ?
              AND (org_id = ? OR org_id IS NULL)
            ORDER BY COALESCE(template_key,event_key) ASC
        ", [$cid, $orgId]);

        $logs = $this->rows("
            SELECT *
            FROM conference_import_logs
            WHERE conference_id = ?
              AND (org_id = ? OR org_id IS NULL)
            ORDER BY id DESC
            LIMIT 10
        ", [$cid, $orgId]);

        $sections = $sections ?? [];
        ob_start();
        require BASE_PATH . '/app/views/admin/conference_home/index.php';
        $content = ob_get_clean();

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

    public function setPolicy()
    {
        $this->requireAccess();

        if (!in_array($this->role(), ['superadmin','org_admin'], true)) {
            http_response_code(403);
            exit("Only superadmin or organization admin can set policy.");
        }

        $conference = $this->conference();
        $orgId = (int)$conference['org_id'];
        $conferenceId = (int)($_POST['conference_id'] ?? $conference['id']);

        $stmt = $this->db()->prepare("
            SELECT id
            FROM conferences
            WHERE id = ?
              AND org_id = ?
            LIMIT 1
        ");
        $stmt->execute([$conferenceId, $orgId]);

        if (!$stmt->fetchColumn()) {
            exit("Invalid conference for this organization.");
        }

        $stmt = $this->db()->prepare("
            INSERT INTO org_conference_policy (org_id, conference_id, policy_note, created_by)
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                conference_id = VALUES(conference_id),
                policy_note = VALUES(policy_note),
                updated_at = NOW()
        ");
        $stmt->execute([
            $orgId,
            $conferenceId,
            trim($_POST['policy_note'] ?? 'Updated from smart home'),
            (int)$_SESSION['user_id']
        ]);

        header("Location: /easychair/admin/conference-home/sections");
        exit;
    }

    public function storeBlock()
    {
        $this->requireAccess();

        $conference = $this->conference();
        $imagePath = null;

        if (!empty($_FILES['image']['name']) && is_uploaded_file($_FILES['image']['tmp_name'])) {
            $dir = BASE_PATH . '/public/storage/home/' . (int)$conference['id'];

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

            $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            $ext = preg_replace('/[^a-z0-9]/', '', $ext);
            $file = 'block_' . time() . '_' . rand(1000,9999) . '.' . $ext;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $dir . '/' . $file)) {
                $imagePath = 'home/' . (int)$conference['id'] . '/' . $file;
            }
        }

$stmt = $this->db()->prepare("
    INSERT INTO conference_homepage_blocks
    (
        conference_id,
        block_type,
        title_ar,
        title_en,
        body_ar,
        body_en,
        image_path,
        link_url,
        sort_order,
        is_active,
        block_key,
        org_id
    )
    VALUES
    (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?
    )
");
       
 
$stmt->execute([

    (int)$conference['id'],

    (
        in_array(
            ($_POST['block_type'] ?? 'section_html'),
            [
                'hero_slide',
                'panel',
                'topic',
                'section_html',
                'important_date'
            ],
            true
        )
            ? $_POST['block_type']
            : 'section_html'
    ),

    trim($_POST['title_ar'] ?? ''),
    trim($_POST['title_en'] ?? ''),

    trim($_POST['body_ar'] ?? ''),
    trim($_POST['body_en'] ?? ''),

    $imagePath,

    trim($_POST['link_url'] ?? ''),

    (int)($_POST['sort_order'] ?? 1),

    'block_' . time(),

    (int)$conference['org_id']
]);

        header("Location: /easychair/admin/conference-home/sections");
        exit;
    }

    public function toggleBlock()
    {
        $this->requireAccess();
        $conference = $this->conference();

        
$stmt = $this->db()->prepare("
    UPDATE conference_homepage_blocks
    SET is_active = IF(is_active=1,0,1)
    WHERE id = ?
      AND conference_id = ?
");

$stmt->execute([
    (int)($_GET['id'] ?? 0),
    (int)$conference['id']
]);

        header("Location: /easychair/admin/conference-home/sections");
        exit;
    }

    public function deleteBlock()
    {
        $this->requireAccess();
        $conference = $this->conference();

$stmt = $this->db()->prepare("
    DELETE FROM conference_homepage_blocks
    WHERE id = ?
      AND conference_id = ?
");
   

$stmt->execute([
    (int)($_GET['id'] ?? 0),
    (int)$conference['id']
]);

        header("Location: /easychair/admin/conference-home/sections");
        exit;
    }

    public function saveTemplate()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $key = trim($_POST['template_key'] ?? '');

        if ($key === '') {
            exit("Template key required.");
        }

        $stmt = $this->db()->prepare("
            INSERT INTO conference_email_templates
            (org_id, conference_id, event_key, template_key, subject_ar, subject_en, body_ar, body_en, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
            ON DUPLICATE KEY UPDATE
                subject_ar = VALUES(subject_ar),
                subject_en = VALUES(subject_en),
                body_ar = VALUES(body_ar),
                body_en = VALUES(body_en),
                updated_at = NOW()
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $key,
            $key,
            trim($_POST['subject_ar'] ?? ''),
            trim($_POST['subject_en'] ?? ''),
            trim($_POST['body_ar'] ?? ''),
            trim($_POST['body_en'] ?? '')
        ]);

        header("Location: /easychair/admin/conference-home#email-templates");
        exit;
    }

    private function csvRows(string $file): array
    {
        $rows = [];

        if (($h = fopen($file, 'r')) === false) {
            return $rows;
        }

        $header = fgetcsv($h);

        if (!$header) {
            fclose($h);
            return $rows;
        }

        $header = array_map(fn($v) => trim(strtolower((string)$v)), $header);

        while (($data = fgetcsv($h)) !== false) {
            $row = [];
            foreach ($header as $i => $key) {
                $row[$key] = $data[$i] ?? '';
            }
            $rows[] = $row;
        }

        fclose($h);
        return $rows;
    }

    public function uploadReviewersCsv()
    {
        $this->requireAccess();

        $conference = $this->conference();

        if (empty($_FILES['csv']['tmp_name'])) {
            exit("CSV file required.");
        }

        $rows = $this->csvRows($_FILES['csv']['tmp_name']);

        $stmt = $this->db()->prepare("SELECT id FROM roles WHERE code='reviewer' LIMIT 1");
        $stmt->execute();
        $reviewerRoleId = (int)$stmt->fetchColumn();

        $inserted = 0;
        $updated = 0;
        $skipped = 0;
        $errors = [];

        foreach ($rows as $idx => $r) {
            $email = trim($r['email'] ?? '');

            if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $skipped++;
                $errors[] = "Row " . ($idx + 2) . ": invalid email";
                continue;
            }

            $first = trim($r['first_name'] ?? $r['firstname'] ?? $r['name'] ?? 'Reviewer');
            $last = trim($r['last_name'] ?? $r['lastname'] ?? '');
            $mobile = trim($r['mobile'] ?? $r['phone'] ?? '');
            $job = trim($r['job_title'] ?? $r['title'] ?? 'Reviewer');
            $expertise = trim($r['expertise'] ?? '');

            $stmt = $this->db()->prepare("SELECT id FROM users WHERE email=? LIMIT 1");
            $stmt->execute([$email]);
            $userId = (int)$stmt->fetchColumn();

            if ($userId > 0) {
                $stmt = $this->db()->prepare("
                    UPDATE users
                    SET org_id = ?,
                        role_id = ?,
                        first_name = COALESCE(NULLIF(?,''), first_name),
                        last_name = COALESCE(NULLIF(?,''), last_name),
                        mobile = COALESCE(NULLIF(?,''), mobile),
                        job_title = COALESCE(NULLIF(?,''), job_title),
                        expertise = COALESCE(NULLIF(?,''), expertise),
                        is_active = 1
                    WHERE id = ?
                ");
                $stmt->execute([(int)$conference['org_id'], $reviewerRoleId, $first, $last, $mobile, $job, $expertise, $userId]);
                $updated++;
            } else {
                $password = trim($r['password'] ?? 'Test@12345');

                $stmt = $this->db()->prepare("
                    INSERT INTO users
                    (org_id, role_id, first_name, last_name, email, password_hash, mobile, job_title, preferred_lang, is_active, expertise, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'en', 1, ?, NOW())
                ");
                $stmt->execute([
                    (int)$conference['org_id'],
                    $reviewerRoleId,
                    $first ?: 'Reviewer',
                    $last,
                    $email,
                    password_hash($password, PASSWORD_BCRYPT),
                    $mobile,
                    $job,
                    $expertise
                ]);
                $userId = (int)$this->db()->lastInsertId();
                $inserted++;
            }

            $stmt = $this->db()->prepare("
                SELECT id
                FROM user_conferences
                WHERE user_id = ?
                  AND conference_id = ?
                LIMIT 1
            ");
            $stmt->execute([$userId, (int)$conference['id']]);

            if ($stmt->fetchColumn()) {
                $stmt = $this->db()->prepare("
                    UPDATE user_conferences
                    SET role_id = ?
                    WHERE user_id = ?
                      AND conference_id = ?
                ");
                $stmt->execute([$reviewerRoleId, $userId, (int)$conference['id']]);
            } else {
                $stmt = $this->db()->prepare("
                    INSERT INTO user_conferences (user_id, conference_id, role_id)
                    VALUES (?, ?, ?)
                ");
                $stmt->execute([$userId, (int)$conference['id'], $reviewerRoleId]);
            }
        }

        $stmt = $this->db()->prepare("
            INSERT INTO conference_import_logs
            (org_id, conference_id, import_type, filename, total_rows, inserted_rows, updated_rows, skipped_rows, errors, created_by)
            VALUES (?, ?, 'reviewers_csv', ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $_FILES['csv']['name'] ?? '',
            count($rows),
            $inserted,
            $updated,
            $skipped,
            implode("\n", $errors),
            (int)$_SESSION['user_id']
        ]);

        header("Location: /easychair/admin/conference-home#imports");
        exit;
    }

    public function uploadCommitteesCsv()
    {
        $this->requireAccess();

        $conference = $this->conference();

        if (empty($_FILES['csv']['tmp_name'])) {
            exit("CSV file required.");
        }

        $rows = $this->csvRows($_FILES['csv']['tmp_name']);

        $inserted = 0;
        $updated = 0;
        $skipped = 0;
        $errors = [];

        foreach ($rows as $idx => $r) {
            $email = trim($r['email'] ?? '');
            $nameAr = trim($r['full_name_ar'] ?? $r['name_ar'] ?? '');
            $nameEn = trim($r['full_name_en'] ?? $r['name_en'] ?? $r['name'] ?? '');

            if (!$nameAr && !$nameEn && !$email) {
                $skipped++;
                $errors[] = "Row " . ($idx + 2) . ": missing name/email";
                continue;
            }

            $type = trim($r['committee_type'] ?? 'committee');

            $stmt = $this->db()->prepare("
                SELECT id
                FROM conference_committees
                WHERE conference_id = ?
                  AND (org_id = ? OR org_id IS NULL)
                  AND email = ?
                  AND email <> ''
                LIMIT 1
            ");
            $stmt->execute([(int)$conference['id'], (int)$conference['org_id'], $email]);
            $id = (int)$stmt->fetchColumn();

            if ($id > 0) {
                $stmt = $this->db()->prepare("
                    UPDATE conference_committees
                    SET committee_type = ?,
                        full_name_ar = ?,
                        full_name_en = ?,
                        title_ar = ?,
                        title_en = ?,
                        affiliation_ar = ?,
                        affiliation_en = ?,
                        sort_order = ?,
                        is_active = 1,
                        org_id = ?
                    WHERE id = ?
                ");
                $stmt->execute([
                    $type,
                    $nameAr,
                    $nameEn,
                    trim($r['title_ar'] ?? ''),
                    trim($r['title_en'] ?? ''),
                    trim($r['affiliation_ar'] ?? ''),
                    trim($r['affiliation_en'] ?? ''),
                    (int)($r['sort_order'] ?? 1),
                    (int)$conference['org_id'],
                    $id
                ]);
                $updated++;
            } else {
                $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, sort_order, is_active, created_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
                ");
                $stmt->execute([
                    (int)$conference['org_id'],
                    (int)$conference['id'],
                    $type,
                    $nameAr,
                    $nameEn,
                    trim($r['title_ar'] ?? ''),
                    trim($r['title_en'] ?? ''),
                    trim($r['affiliation_ar'] ?? ''),
                    trim($r['affiliation_en'] ?? ''),
                    $email,
                    (int)($r['sort_order'] ?? 1),
                    (int)$_SESSION['user_id']
                ]);
                $inserted++;
            }
        }

        $stmt = $this->db()->prepare("
            INSERT INTO conference_import_logs
            (org_id, conference_id, import_type, filename, total_rows, inserted_rows, updated_rows, skipped_rows, errors, created_by)
            VALUES (?, ?, 'committees_csv', ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $_FILES['csv']['name'] ?? '',
            count($rows),
            $inserted,
            $updated,
            $skipped,
            implode("\n", $errors),
            (int)$_SESSION['user_id']
        ]);

        header("Location: /easychair/admin/conference-home#imports");
        exit;
    }

    public function addTemplate()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $key = trim($_POST['template_key'] ?? '');

        if ($key === '') {
            exit("Template key required.");
        }

        $stmt = $this->db()->prepare("
            INSERT INTO conference_email_templates
            (org_id, conference_id, event_key, template_key, subject_ar, subject_en, body_ar, body_en, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
            ON DUPLICATE KEY UPDATE
                subject_ar = VALUES(subject_ar),
                subject_en = VALUES(subject_en),
                body_ar = VALUES(body_ar),
                body_en = VALUES(body_en),
                updated_at = NOW()
        ");

        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $key,
            $key,
            trim($_POST['subject_ar'] ?? ''),
            trim($_POST['subject_en'] ?? ''),
            trim($_POST['body_ar'] ?? ''),
            trim($_POST['body_en'] ?? '')
        ]);

        header("Location: /easychair/admin/conference-home#email-templates");
        exit;
    }

    public function toggleTemplate()
    {
        $this->requireAccess();
        $conference = $this->conference();

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

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

        header("Location: /easychair/admin/conference-home#email-templates");
        exit;
    }

    public function deleteTemplate()
    {
        $this->requireAccess();
        $conference = $this->conference();

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

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

        header("Location: /easychair/admin/conference-home#email-templates");
        exit;
    }

    public function toggleSection()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (empty($_SESSION['user_id'])) {

            header("Location: /easychair/login");
            exit;
        }

        $db = Database::getInstance();

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

        if ($id <= 0) {

            $_SESSION['error'] =
                'Invalid section id';

            header(
                "Location: /easychair/admin/conference-home/sections"
            );

            exit;
        }

        try {

            $stmt = $db->prepare("
                UPDATE conference_home_sections

                SET enabled =
                    CASE
                        WHEN enabled = 1 THEN 0
                        ELSE 1
                    END

                WHERE id = ?
                LIMIT 1
            ");

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

            $_SESSION['success'] =
                'Homepage section updated successfully';

        } catch (\Throwable $e) {

            $_SESSION['error'] =
                $e->getMessage();

            error_log(
                'SECTION TOGGLE ERROR: '
                . $e->getMessage()
            );
        }

        header(
            "Location: /easychair/admin/conference-home/sections"
        );

        exit;
    }


public function toggleSectionAjax()
{
    //$this->requireSuperAdmin();

    header('Content-Type: application/json');

    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        UPDATE conference_home_sections

        SET enabled =
            CASE
                WHEN enabled = 1 THEN 0
                ELSE 1
            END

        WHERE id = ?
        LIMIT 1

    ");

    $ok = $stmt->execute([$id]);

    echo json_encode([
        'success' => $ok
    ]);

    exit;
}


public function reorderSectionsAjax()
{
    header('Content-Type: application/json');

    $db = Database::getInstance();

    $items =
        $_POST['items'] ?? [];

    if (!is_array($items)) {

        echo json_encode([
            'success' => false
        ]);

        exit;
    }

    $stmt = $db->prepare("

        UPDATE conference_home_sections

        SET sort_order = ?

        WHERE id = ?

    ");

    $sort = 1;

    foreach ($items as $id) {

        $stmt->execute([
            $sort,
            (int)$id
        ]);

        $sort++;
    }

    echo json_encode([
        'success' => true
    ]);

    exit;
}

public function sections()
{
    $db = Database::getInstance();

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections
        WHERE conference_id = ?
        ORDER BY sort_order ASC, id ASC

    ");

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

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

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/sections.php';

    $content =
        ob_get_clean();

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

public function editSection()
{
    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections
        WHERE id = ?
        LIMIT 1

    ");

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

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

    if (!$section) {
        die('Section not found');
    }

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/edit_section.php';

    $content =
        ob_get_clean();

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

public function updateSection()
{
    $db = Database::getInstance();

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

$backgroundImage =
    $_POST['existing_background_image']
    ?? '';

if (
    !empty($_FILES['background_image']['name'])
) {

    $dir =
        BASE_PATH .
        '/public/uploads/section_backgrounds/';

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

    $ext =
        pathinfo(
            $_FILES['background_image']['name'],
            PATHINFO_EXTENSION
        );

    $file =
        'section_' .
        time() .
        '_' .
        rand(1000,9999) .
        '.' .
        $ext;

    move_uploaded_file(
        $_FILES['background_image']['tmp_name'],
        $dir . $file
    );

    $backgroundImage =
        $file;
}
    $stmt = $db->prepare("

        UPDATE conference_home_sections

        SET

            section_title_en = ?,
            section_title_ar = ?,

            title_en = ?,
            title_ar = ?,

            subtitle_en = ?,
            subtitle_ar = ?,

            icon_class = ?,
            theme_name = ?,
background_type = ?,
background_value = ?,
custom_css_class = ?,
background_image = ?,
            sort_order = ?,
            enabled = ?

        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([

        trim($_POST['section_title_en'] ?? ''),
        trim($_POST['section_title_ar'] ?? ''),

        trim($_POST['title_en'] ?? ''),
        trim($_POST['title_ar'] ?? ''),

        trim($_POST['subtitle_en'] ?? ''),
        trim($_POST['subtitle_ar'] ?? ''),

        trim($_POST['icon_class'] ?? ''),

        trim($_POST['theme_name'] ?? 'enterprise-gradient'),
trim($_POST['background_type'] ?? 'gradient'),

trim($_POST['background_value'] ?? ''),

trim($_POST['custom_css_class'] ?? ''),
        
$backgroundImage,
(int)($_POST['sort_order'] ?? 0),

        !empty($_POST['enabled']) ? 1 : 0,

        $id

    ]);

    $_SESSION['success'] =
        'Homepage section updated successfully';

    header(
        'Location: /easychair/admin/conference-home/sections'
    );

    exit;
}

public function createSection()
{
    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/create_section.php';

    $content =
        ob_get_clean();

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

public function storeSection()
{
    $db = Database::getInstance();

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    $stmt = $db->prepare("

        INSERT INTO conference_home_sections
        (

            conference_id,

            section_key,

            section_title_en,
            section_title_ar,

            title_en,
            title_ar,

            subtitle_en,
            subtitle_ar,

            icon_class,

            theme_name,

            sort_order,

            enabled

        )

        VALUES
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

    ");

    $stmt->execute([

        $conferenceId,

        trim($_POST['section_key'] ?? ''),

        trim($_POST['section_title_en'] ?? ''),
        trim($_POST['section_title_ar'] ?? ''),

        trim($_POST['title_en'] ?? ''),
        trim($_POST['title_ar'] ?? ''),

        trim($_POST['subtitle_en'] ?? ''),
        trim($_POST['subtitle_ar'] ?? ''),

        trim($_POST['icon_class'] ?? 'fa-cube'),

        trim($_POST['theme_name'] ?? 'enterprise-gradient'),

        (int)($_POST['sort_order'] ?? 0),

        !empty($_POST['enabled']) ? 1 : 0

    ]);

    $_SESSION['success'] =
        'Homepage section created successfully';

    header(
        'Location: /easychair/admin/conference-home/sections'
    );

    exit;
}

public function deleteSection()
{
    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        DELETE FROM conference_home_sections
        WHERE id = ?
        LIMIT 1

    ");

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

    $_SESSION['success'] =
        'Homepage section deleted';

    header(
        'Location: /easychair/admin/conference-home/sections'
    );

    exit;
}

public function moveSectionUp()
{
    $this->moveSection(-1);
}

public function moveSectionDown()
{
    $this->moveSection(1);
}

private function moveSection(int $direction)
{
    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections
        WHERE id = ?
        LIMIT 1

    ");

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

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

    if (!$current) {
        die('Section not found');
    }

    $operator =
        $direction < 0 ? '<' : '>';

    $sort =
        (int)$current['sort_order'];

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections

        WHERE conference_id = ?
        AND sort_order {$operator} ?

        ORDER BY sort_order " .
        ($direction < 0 ? 'DESC' : 'ASC') . "

        LIMIT 1

    ");

    $stmt->execute([

        $current['conference_id'],
        $sort

    ]);

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

    if ($swap) {

        $stmt = $db->prepare("

            UPDATE conference_home_sections
            SET sort_order = ?
            WHERE id = ?

        ");

        $stmt->execute([
            $swap['sort_order'],
            $current['id']
        ]);

        $stmt->execute([
            $sort,
            $swap['id']
        ]);
    }

    header(
        'Location: /easychair/admin/conference-home/sections'
    );

    exit;
}
public function duplicateSection()
{
    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections
        WHERE id = ?
        LIMIT 1

    ");

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

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

    if (!$section) {

        $_SESSION['error'] =
            'Section not found';

        header(
            'Location: /easychair/admin/conference-home/sections'
        );

        exit;
    }

    unset($section['id']);
    unset($section['created_at']);

    $section['section_key'] =
        $section['section_key'] .
        '_copy_' .
        time();

    $section['section_title_en'] =
        ($section['section_title_en'] ?? '')
        . ' Copy';

    $section['sort_order'] =
        ((int)$section['sort_order']) + 1;

    $columns =
        array_keys($section);

    $sql = "

        INSERT INTO conference_home_sections
        (" . implode(',', $columns) . ")

        VALUES
        (" . implode(',', array_fill(0, count($columns), '?')) . ")

    ";

    $stmt = $db->prepare($sql);

    $stmt->execute(
        array_values($section)
    );

    $_SESSION['success'] =
        'Section duplicated successfully';

    header(
        'Location: /easychair/admin/conference-home/sections'
    );

    exit;
}

/* =========================================================
 * HOMEPAGE BLOCK CMS
 * ========================================================= */

public function blocks()
{
    $db = Database::getInstance();

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    $stmt = $db->prepare("

        SELECT *
        FROM conference_homepage_blocks

        WHERE conference_id = ?

        ORDER BY sort_order ASC, id ASC

    ");

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

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

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/blocks.php';

    $content =
        ob_get_clean();

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

public function createBlock()
{
    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/create_block.php';

    $content =
        ob_get_clean();

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

public function storeBlockCms()
{
    $db = Database::getInstance();

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

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

    $stmt = $db->prepare("

        INSERT INTO conference_homepage_blocks
        (

            conference_id,
            org_id,

            block_type,
            block_key,

            title_en,
            title_ar,

            body_en,
            body_ar,

            button_text_en,
            button_text_ar,

            button_url,

            sort_order,

            is_active

        )

        VALUES
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

    ");

    $stmt->execute([

        $conferenceId,
        $orgId,

        trim($_POST['block_type'] ?? 'panel'),

        trim($_POST['block_key'] ?? ''),

        trim($_POST['title_en'] ?? ''),
        trim($_POST['title_ar'] ?? ''),

        trim($_POST['body_en'] ?? ''),
        trim($_POST['body_ar'] ?? ''),

        trim($_POST['button_text_en'] ?? ''),
        trim($_POST['button_text_ar'] ?? ''),

        trim($_POST['button_url'] ?? ''),

        (int)($_POST['sort_order'] ?? 0),

        !empty($_POST['is_active']) ? 1 : 0

    ]);

    $_SESSION['success'] =
        'Homepage block created successfully';

    header(
        'Location: /easychair/admin/conference-home/blocks'
    );

    exit;
}

public function editBlock()
{
    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        SELECT *
        FROM conference_homepage_blocks

        WHERE id = ?
        LIMIT 1

    ");

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

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

    if (!$block) {
        die('Block not found');
    }

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/edit_block.php';

    $content =
        ob_get_clean();

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

public function updateBlock()
{
    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        UPDATE conference_homepage_blocks

        SET

            block_type = ?,
            block_key = ?,

            title_en = ?,
            title_ar = ?,

            body_en = ?,
            body_ar = ?,

            button_text_en = ?,
            button_text_ar = ?,

            button_url = ?,

            sort_order = ?,

            is_active = ?

        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([

        trim($_POST['block_type'] ?? 'panel'),

        trim($_POST['block_key'] ?? ''),

        trim($_POST['title_en'] ?? ''),
        trim($_POST['title_ar'] ?? ''),

        trim($_POST['body_en'] ?? ''),
        trim($_POST['body_ar'] ?? ''),

        trim($_POST['button_text_en'] ?? ''),
        trim($_POST['button_text_ar'] ?? ''),

        trim($_POST['button_url'] ?? ''),

        (int)($_POST['sort_order'] ?? 0),

        !empty($_POST['is_active']) ? 1 : 0,

        $id

    ]);

    $_SESSION['success'] =
        'Homepage block updated successfully';

    header(
        'Location: /easychair/admin/conference-home/blocks'
    );

    exit;
}

public function deleteBlockCms()
{
    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        DELETE FROM conference_homepage_blocks

        WHERE id = ?
        LIMIT 1

    ");

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

    $_SESSION['success'] =
        'Homepage block deleted';

    header(
        'Location: /easychair/admin/conference-home/blocks'
    );

    exit;
}

public function toggleBlockCms()
{
    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        UPDATE conference_homepage_blocks

        SET is_active =
            CASE
                WHEN is_active = 1 THEN 0
                ELSE 1
            END

        WHERE id = ?
        LIMIT 1

    ");

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

    $_SESSION['success'] =
        'Homepage block updated';

    header(
        'Location: /easychair/admin/conference-home/blocks'
    );

    exit;
}

public function moveBlockUp()
{
    $this->moveBlock(-1);
}

public function moveBlockDown()
{
    $this->moveBlock(1);
}

private function moveBlock(int $direction)
{
    $db = Database::getInstance();

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

    $stmt = $db->prepare("

        SELECT *
        FROM conference_homepage_blocks

        WHERE id = ?
        LIMIT 1

    ");

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

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

    if (!$current) {
        die('Block not found');
    }

    $operator =
        $direction < 0 ? '<' : '>';

    $sort =
        (int)$current['sort_order'];

    $stmt = $db->prepare("

        SELECT *
        FROM conference_homepage_blocks

        WHERE conference_id = ?
        AND sort_order {$operator} ?

        ORDER BY sort_order " .
        ($direction < 0 ? 'DESC' : 'ASC') . "

        LIMIT 1

    ");

    $stmt->execute([
        (int)$current['conference_id'],
        $sort
    ]);

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

    if (!$swap) {

        header(
            'Location: /easychair/admin/conference-home/blocks'
        );

        exit;
    }

    $stmt = $db->prepare("

        UPDATE conference_homepage_blocks
        SET sort_order = ?
        WHERE id = ?

    ");

    $stmt->execute([
        (int)$swap['sort_order'],
        (int)$current['id']
    ]);

    $stmt->execute([
        $sort,
        (int)$swap['id']
    ]);

    $_SESSION['success'] =
        'Homepage block reordered';

    header(
        'Location: /easychair/admin/conference-home/blocks'
    );

    exit;
}

}
