<?php
declare(strict_types=1);

namespace App\Controllers;

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

use App\Core\Controller;
use App\Core\Database;
use App\Models\Conference;
use App\Models\ConferenceBlockModel;
use App\Models\ConferenceCommitteeModel;

final class ConferenceContentController extends Controller
{
    public function blocksIndex(): void
    {
        require_permission('conference_blocks.view');

        $conferenceId = (int)
\request_conference_id();
        $conference = $conferenceId > 0 ? (new Conference())->findById($conferenceId) : null;

        $this->view('admin/conference_blocks/index', [
            'conferences' => (new Conference())->all(),
            'conference' => $conference,
            'rows' => $conference ? (new ConferenceBlockModel())->byConference($conferenceId) : [],
        ]);
    }

    public function blockCreate(): void
    {
        require_permission('conference_blocks.manage');
        $conferences = (new Conference())->all();

        if ($this->isPost()) {
            csrf_check();

            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'block_type' => trim((string) ($_POST['block_type'] ?? 'panel')),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'body_en' => trim((string) ($_POST['body_en'] ?? '')),
                'body_ar' => trim((string) ($_POST['body_ar'] ?? '')),
                'image_path' => trim((string) ($_POST['image_path'] ?? '')),
                'link_url' => trim((string) ($_POST['link_url'] ?? '')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            if (!empty($_FILES['image_file']['name'])) {
                $upload = handle_uploaded_submission_file($_FILES['image_file'], 'conference/blocks');
                $data['image_path'] = base_path('../storage/' . $upload['relative_path']);
            }

            (new ConferenceBlockModel())->create($data);

            flash('success', trans('save'));
            redirect('admin/conference-blocks?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/conference_blocks/create', ['conferences' => $conferences]);
    }

    public function blockEdit(): void
    {
        require_permission('conference_blocks.manage');

        $id = (int) ($_GET['id'] ?? 0);
        $model = new ConferenceBlockModel();
        $row = $model->findById($id);

        if (!$row) {
            redirect('admin/conference-blocks');
        }

        if ($this->isPost()) {
            csrf_check();

            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'block_type' => trim((string) ($_POST['block_type'] ?? 'panel')),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'body_en' => trim((string) ($_POST['body_en'] ?? '')),
                'body_ar' => trim((string) ($_POST['body_ar'] ?? '')),
                'image_path' => trim((string) ($_POST['image_path_existing'] ?? ($row['image_path'] ?? ''))),
                'link_url' => trim((string) ($_POST['link_url'] ?? '')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            if (!empty($_FILES['image_file']['name'])) {
                $upload = handle_uploaded_submission_file($_FILES['image_file'], 'conference/blocks');
                $data['image_path'] = base_path('../storage/' . $upload['relative_path']);
            }

            $model->update($id, $data);

            flash('success', trans('save'));
            redirect('admin/conference-blocks?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/conference_blocks/edit', [
            'row' => $row,
            'conferences' => (new Conference())->all(),
        ]);
    }

    public function committeesIndex(): void
    {
        require_permission('conference_committees.view');

        $conferenceId = (int)
\request_conference_id();
        $conference = $conferenceId > 0 ? (new Conference())->findById($conferenceId) : null;

        $this->view('admin/conference_committees/index', [
            'conferences' => (new Conference())->all(),
            'conference' => $conference,
            'rows' => $conference ? (new ConferenceCommitteeModel())->byConference($conferenceId) : [],
        ]);
    }

    public function committeeCreate(): void
    {
        require_permission('conference_committees.manage');
        $conferences = (new Conference())->all();

        if ($this->isPost()) {
            csrf_check();

            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'committee_type' => trim((string) ($_POST['committee_type'] ?? 'other')),
                'full_name_en' => trim((string) ($_POST['full_name_en'] ?? '')),
                'full_name_ar' => trim((string) ($_POST['full_name_ar'] ?? '')),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'affiliation_en' => trim((string) ($_POST['affiliation_en'] ?? '')),
                'affiliation_ar' => trim((string) ($_POST['affiliation_ar'] ?? '')),
                'email' => trim((string) ($_POST['email'] ?? '')),
                'image_path' => trim((string) ($_POST['image_path'] ?? '')),
                'bio_en' => trim((string) ($_POST['bio_en'] ?? '')),
                'bio_ar' => trim((string) ($_POST['bio_ar'] ?? '')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            if ($data['conference_id'] <= 0 || $data['full_name_en'] === '') {
                flash('danger', trans('required_fields'));
                redirect('admin/conference-committees/create');
            }

            if (!empty($_FILES['image_file']['name'])) {
                $upload = handle_uploaded_submission_file($_FILES['image_file'], 'conference/committees');
                $data['image_path'] = base_path('../storage/' . $upload['relative_path']);
            }

            (new ConferenceCommitteeModel())->create($data);

            flash('success', trans('save'));
            redirect('admin/conference-committees?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/conference_committees/create', ['conferences' => $conferences]);
    }

    public function committeeEdit(): void
    {
        require_permission('conference_committees.manage');

        $id = (int) ($_GET['id'] ?? 0);
        $model = new ConferenceCommitteeModel();
        $row = $model->findById($id);

        if (!$row) {
            redirect('admin/conference-committees');
        }

        if ($this->isPost()) {
            csrf_check();

            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'committee_type' => trim((string) ($_POST['committee_type'] ?? 'other')),
                'full_name_en' => trim((string) ($_POST['full_name_en'] ?? '')),
                'full_name_ar' => trim((string) ($_POST['full_name_ar'] ?? '')),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'affiliation_en' => trim((string) ($_POST['affiliation_en'] ?? '')),
                'affiliation_ar' => trim((string) ($_POST['affiliation_ar'] ?? '')),
                'email' => trim((string) ($_POST['email'] ?? '')),
                'image_path' => trim((string) ($_POST['image_path_existing'] ?? ($row['image_path'] ?? ''))),
                'bio_en' => trim((string) ($_POST['bio_en'] ?? '')),
                'bio_ar' => trim((string) ($_POST['bio_ar'] ?? '')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            if (!empty($_FILES['image_file']['name'])) {
                $upload = handle_uploaded_submission_file($_FILES['image_file'], 'conference/committees');
                $data['image_path'] = base_path('../storage/' . $upload['relative_path']);
            }

            $model->update($id, $data);

            flash('success', trans('save'));
            redirect('admin/conference-committees?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/conference_committees/edit', [
            'row' => $row,
            'conferences' => (new Conference())->all(),
        ]);
    }

    public function committeeBulk(): void
    {
        require_permission('conference_committees.bulk_import');

        if ($this->isPost()) {
            csrf_check();

            if (empty($_FILES['csv_file']['name'])) {
                flash('danger', trans('required_fields'));
                redirect('admin/conference-committees/bulk');
            }

            $upload = handle_uploaded_submission_file($_FILES['csv_file'], 'imports/committees');
            $path = storage_path($upload['relative_path']);

            $created = 0;
            if (($fh = fopen($path, 'r')) !== false) {
                $header = fgetcsv($fh);
                while (($row = fgetcsv($fh)) !== false) {
                    if (!$header || count($header) !== count($row)) {
                        continue;
                    }
                    $data = array_combine($header, $row);
                    if (!$data || empty($data['conference_id']) || empty($data['full_name_en'])) {
                        continue;
                    }

                    (new ConferenceCommitteeModel())->create([
                        'conference_id' => (int) ($data['conference_id'] ?? 0),
                        'committee_type' => trim((string) ($data['committee_type'] ?? 'other')),
                        'full_name_en' => trim((string) ($data['full_name_en'] ?? '')),
                        'full_name_ar' => trim((string) ($data['full_name_ar'] ?? '')),
                        'title_en' => trim((string) ($data['title_en'] ?? '')),
                        'title_ar' => trim((string) ($data['title_ar'] ?? '')),
                        'affiliation_en' => trim((string) ($data['affiliation_en'] ?? '')),
                        'affiliation_ar' => trim((string) ($data['affiliation_ar'] ?? '')),
                        'email' => trim((string) ($data['email'] ?? '')),
                        'image_path' => trim((string) ($data['image_path'] ?? '')),
                        'bio_en' => trim((string) ($data['bio_en'] ?? '')),
                        'bio_ar' => trim((string) ($data['bio_ar'] ?? '')),
                        'sort_order' => (int) ($data['sort_order'] ?? 0),
                        'is_active' => (int) ($data['is_active'] ?? 1),
                    ]);
                    $created++;
                }
                fclose($fh);
            }

            flash('success', trans('committees_imported_success') . ' ' . $created);
            redirect('admin/conference-committees');
        }

        $this->view('admin/conference_committees/bulk', [
            'conferences' => (new Conference())->all(),
        ]);
    }

    public function blockSort(): void
    {
        require_permission('conference_blocks.manage');

        if (!$this->isPost()) {
            redirect('admin/conference-blocks');
        }

        csrf_check();

        $ids = $_POST['ordered_ids'] ?? [];
        $ids = is_array($ids) ? array_map('intval', $ids) : [];

        $db = Database::getInstance();
        $stmt = $db->prepare("UPDATE conference_blocks SET sort_order = :sort_order WHERE id = :id");
        $sort = 1;
        foreach ($ids as $id) {
            $stmt->execute([':sort_order' => $sort++, ':id' => $id]);
        }

        flash('success', trans('save'));
        redirect('admin/conference-blocks?conference_id=' . (int) ($_POST['conference_id'] ?? 0));
    }

    public function committeeSort(): void
    {
        require_permission('conference_committees.manage');

        if (!$this->isPost()) {
            redirect('admin/conference-committees');
        }

        csrf_check();

        $ids = $_POST['ordered_ids'] ?? [];
        $ids = is_array($ids) ? array_map('intval', $ids) : [];

        $db = Database::getInstance();
        $stmt = $db->prepare("UPDATE conference_committees SET sort_order = :sort_order WHERE id = :id");
        $sort = 1;
        foreach ($ids as $id) {
            $stmt->execute([':sort_order' => $sort++, ':id' => $id]);
        }

        flash('success', trans('save'));
        redirect('admin/conference-committees?conference_id=' . (int) ($_POST['conference_id'] ?? 0));
    }
}
