<?php
declare(strict_types=1);

namespace App\Controllers;

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

use App\Core\Controller;
use App\Models\ScheduleModel;

final class ScheduleController extends Controller
{
    public function index(): void
    {
        require_permission('conference_schedule.view');

        $conferenceId = (int)
\request_conference_id();
        $model = new ScheduleModel();

        $conference = $conferenceId > 0 ? $model->conferenceById($conferenceId) : null;

        $this->view('admin/schedule/index', [
            'conferences' => $model->conferences(),
            'conference' => $conference,
            'days' => $conference ? $model->daysByConference($conferenceId) : [],
            'sessions' => $conference ? $model->sessionsByConference($conferenceId) : [],
            'badges' => $conference ? $model->badgesByConference($conferenceId) : [],
        ]);
    }

    public function dayCreate(): void
    {
        require_permission('conference_schedule.manage');
        $model = new ScheduleModel();

        if ($this->isPost()) {
            csrf_check();
            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'day_date' => trim((string) ($_POST['day_date'] ?? '')),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];
            $model->createDay($data);
            flash('success', trans('save'));
            redirect('admin/schedule?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/schedule/day_create', [
            'conferences' => $model->conferences(),
        ]);
    }

    public function dayEdit(): void
    {
        require_permission('conference_schedule.manage');
        $model = new ScheduleModel();
        $id = (int) ($_GET['id'] ?? 0);
        $row = $model->dayById($id);
        if (!$row) redirect('admin/schedule');

        if ($this->isPost()) {
            csrf_check();
            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'day_date' => trim((string) ($_POST['day_date'] ?? '')),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];
            $model->updateDay($id, $data);
            flash('success', trans('save'));
            redirect('admin/schedule?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/schedule/day_edit', [
            'row' => $row,
            'conferences' => $model->conferences(),
        ]);
    }

    public function sessionCreate(): void
    {
        require_permission('conference_schedule.manage');
        $model = new ScheduleModel();
        $conferenceId = (int) ($_GET['conference_id'] ?? ($_POST['conference_id'] ?? 0));

        if ($this->isPost()) {
            csrf_check();
            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'conference_day_id' => (int) ($_POST['conference_day_id'] ?? 0),
                'track_id' => (int) ($_POST['track_id'] ?? 0),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'hall_en' => trim((string) ($_POST['hall_en'] ?? '')),
                'hall_ar' => trim((string) ($_POST['hall_ar'] ?? '')),
                'chair_name_en' => trim((string) ($_POST['chair_name_en'] ?? '')),
                'chair_name_ar' => trim((string) ($_POST['chair_name_ar'] ?? '')),
                'start_time' => trim((string) ($_POST['start_time'] ?? '')),
                'end_time' => trim((string) ($_POST['end_time'] ?? '')),
                'session_type' => trim((string) ($_POST['session_type'] ?? 'technical')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];
            $model->createSession($data);
            flash('success', trans('save'));
            redirect('admin/schedule?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/schedule/session_create', [
            'conferences' => $model->conferences(),
            'days' => $conferenceId > 0 ? $model->daysByConference($conferenceId) : [],
            'tracks' => $conferenceId > 0 ? $model->tracksByConference($conferenceId) : [],
            'conference_id' => $conferenceId,
        ]);
    }

    public function sessionEdit(): void
    {
        require_permission('conference_schedule.manage');
        $model = new ScheduleModel();
        $id = (int) ($_GET['id'] ?? 0);
        $row = $model->sessionById($id);
        if (!$row) redirect('admin/schedule');

        if ($this->isPost()) {
            csrf_check();
            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'conference_day_id' => (int) ($_POST['conference_day_id'] ?? 0),
                'track_id' => (int) ($_POST['track_id'] ?? 0),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'hall_en' => trim((string) ($_POST['hall_en'] ?? '')),
                'hall_ar' => trim((string) ($_POST['hall_ar'] ?? '')),
                'chair_name_en' => trim((string) ($_POST['chair_name_en'] ?? '')),
                'chair_name_ar' => trim((string) ($_POST['chair_name_ar'] ?? '')),
                'start_time' => trim((string) ($_POST['start_time'] ?? '')),
                'end_time' => trim((string) ($_POST['end_time'] ?? '')),
                'session_type' => trim((string) ($_POST['session_type'] ?? 'technical')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];
            $model->updateSession($id, $data);
            flash('success', trans('save'));
            redirect('admin/schedule?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/schedule/session_edit', [
            'row' => $row,
            'conferences' => $model->conferences(),
            'days' => $model->daysByConference((int) $row['conference_id']),
            'tracks' => $model->tracksByConference((int) $row['conference_id']),
        ]);
    }

    public function presentationCreate(): void
    {
        require_permission('conference_schedule.manage');
        $model = new ScheduleModel();
        $sessionId = (int) ($_GET['session_id'] ?? ($_POST['session_id'] ?? 0));
        $session = $sessionId > 0 ? $model->sessionById($sessionId) : null;
        if (!$session) redirect('admin/schedule');

        if ($this->isPost()) {
            csrf_check();
            $data = [
                'session_id' => (int) ($_POST['session_id'] ?? 0),
                'submission_id' => (int) ($_POST['submission_id'] ?? 0),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'presenter_name_en' => trim((string) ($_POST['presenter_name_en'] ?? '')),
                'presenter_name_ar' => trim((string) ($_POST['presenter_name_ar'] ?? '')),
                'presenter_email' => trim((string) ($_POST['presenter_email'] ?? '')),
                'start_time' => trim((string) ($_POST['start_time'] ?? '')),
                'end_time' => trim((string) ($_POST['end_time'] ?? '')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];
            $model->createPresentation($data);
            flash('success', trans('save'));
            redirect('admin/schedule?conference_id=' . (int) $session['conference_id']);
        }

        $this->view('admin/schedule/presentation_create', [
            'session' => $session,
            'submissions' => $model->acceptedSubmissions((int) $session['conference_id']),
        ]);
    }

    public function presentationEdit(): void
    {
        require_permission('conference_schedule.manage');
        $model = new ScheduleModel();
        $id = (int) ($_GET['id'] ?? 0);
        $row = $model->presentationById($id);
        if (!$row) redirect('admin/schedule');
        $session = $model->sessionById((int) $row['session_id']);
        if (!$session) redirect('admin/schedule');

        if ($this->isPost()) {
            csrf_check();
            $data = [
                'session_id' => (int) ($_POST['session_id'] ?? 0),
                'submission_id' => (int) ($_POST['submission_id'] ?? 0),
                'title_en' => trim((string) ($_POST['title_en'] ?? '')),
                'title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                'presenter_name_en' => trim((string) ($_POST['presenter_name_en'] ?? '')),
                'presenter_name_ar' => trim((string) ($_POST['presenter_name_ar'] ?? '')),
                'presenter_email' => trim((string) ($_POST['presenter_email'] ?? '')),
                'start_time' => trim((string) ($_POST['start_time'] ?? '')),
                'end_time' => trim((string) ($_POST['end_time'] ?? '')),
                'sort_order' => (int) ($_POST['sort_order'] ?? 0),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];
            $model->updatePresentation($id, $data);
            flash('success', trans('save'));
            redirect('admin/schedule?conference_id=' . (int) $session['conference_id']);
        }

        $this->view('admin/schedule/presentation_edit', [
            'row' => $row,
            'session' => $session,
            'submissions' => $model->acceptedSubmissions((int) $session['conference_id']),
        ]);
    }

    public function badgesIndex(): void
    {
        require_permission('conference_badges.view');
        $conferenceId = (int)
\request_conference_id();
        $model = new ScheduleModel();
        $conference = $conferenceId > 0 ? $model->conferenceById($conferenceId) : null;

        $this->view('admin/badges/index', [
            'conferences' => $model->conferences(),
            'conference' => $conference,
            'rows' => $conference ? $model->badgesByConference($conferenceId) : [],
        ]);
    }

    public function badgeCreate(): void
    {
        require_permission('conference_badges.manage');
        $model = new ScheduleModel();

        if ($this->isPost()) {
            csrf_check();
            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'person_name_en' => trim((string) ($_POST['person_name_en'] ?? '')),
                'person_name_ar' => trim((string) ($_POST['person_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'] ?? '')),
                'badge_role' => trim((string) ($_POST['badge_role'] ?? 'attendee')),
                'qr_text' => trim((string) ($_POST['qr_text'] ?? '')),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];
            $model->createBadge($data);
            flash('success', trans('save'));
            redirect('admin/badges?conference_id=' . $data['conference_id']);
        }

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

    public function badgeEdit(): void
    {
        require_permission('conference_badges.manage');
        $model = new ScheduleModel();
        $id = (int) ($_GET['id'] ?? 0);
        $row = $model->badgeById($id);
        if (!$row) redirect('admin/badges');

        if ($this->isPost()) {
            csrf_check();
            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'person_name_en' => trim((string) ($_POST['person_name_en'] ?? '')),
                'person_name_ar' => trim((string) ($_POST['person_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'] ?? '')),
                'badge_role' => trim((string) ($_POST['badge_role'] ?? 'attendee')),
                'qr_text' => trim((string) ($_POST['qr_text'] ?? '')),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];
            $model->updateBadge($id, $data);
            flash('success', trans('save'));
            redirect('admin/badges?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/badges/edit', [
            'row' => $row,
            'conferences' => $model->conferences(),
        ]);
    }

    public function publicSchedule(): void
    {
        $slug = trim((string) ($_GET['slug'] ?? ''));
        if ($slug === '') redirect('');

        $model = new ScheduleModel();
        $conference = $model->conferenceBySlug($slug);
        if (!$conference) {
            http_response_code(404);
            exit('Conference not found');
        }

        $sessions = $model->sessionsByConference((int) $conference['id']);
        $presentations = [];
        foreach ($sessions as $session) {
            $presentations[(int) $session['id']] = $model->presentationsBySession((int) $session['id']);
        }

        $this->view('conference/schedule', [
            'conference' => $conference,
            'days' => $model->daysByConference((int) $conference['id']),
            'sessions' => $sessions,
            'presentations' => $presentations,
        ]);
    }

    public function printBadge(): void
    {
        require_permission('conference_badges.view');
        $id = (int) ($_GET['id'] ?? 0);
        $model = new ScheduleModel();
        $badge = $model->badgeById($id);
        if (!$badge) {
            http_response_code(404);
            exit('Badge not found');
        }
        $conference = $model->conferenceById((int) $badge['conference_id']);
        require __DIR__ . '/../views/print/badge.php';
    }

    public function presenterCertificate(): void
    {
        require_permission('conference_certificates.print');
        $id = (int) ($_GET['presentation_id'] ?? 0);
        $model = new ScheduleModel();
        $presentation = $model->presentationById($id);
        if (!$presentation) {
            http_response_code(404);
            exit('Presentation not found');
        }
        $session = $model->sessionById((int) $presentation['session_id']);
        $conference = $session ? $model->conferenceById((int) $session['conference_id']) : null;
        require __DIR__ . '/../views/print/presenter_certificate.php';
    }

    public function attendanceCertificate(): void
    {
        require_permission('conference_certificates.print');
        $id = (int) ($_GET['badge_id'] ?? 0);
        $model = new ScheduleModel();
        $badge = $model->badgeById($id);
        if (!$badge) {
            http_response_code(404);
            exit('Badge not found');
        }
        $conference = $model->conferenceById((int) $badge['conference_id']);
        require __DIR__ . '/../views/print/attendance_certificate.php';
    }
}
