<?php

class ScheduleController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('schedules/index', [
            'title' => lang('reports.scheduled_reports'),
            'breadcrumbs' => [
                ['label' => lang('reports.reports'), 'url' => '/reports'],
                ['label' => lang('reports.scheduled_reports')],
            ],
        ]);
    }

    public function create(Request $request): void
    {
        $db = $this->db();
        $reports = $db->fetchAll("SELECT id, report_code, report_name_en, report_name_ar FROM report_definitions WHERE is_active = 1 AND is_schedulable = 1 ORDER BY report_name_en");

        $this->view('schedules/create', [
            'title' => lang('reports.create_schedule'),
            'breadcrumbs' => [
                ['label' => lang('reports.reports'), 'url' => '/reports'],
                ['label' => lang('reports.scheduled_reports'), 'url' => '/reports/schedules'],
                ['label' => lang('common.create')],
            ],
            'reports' => $reports,
        ]);
    }

    public function edit(Request $request): void
    {
        $db = $this->db();
        $id = (int) $request->routeParam('id');

        $schedule = $db->fetchOne("SELECT * FROM report_schedules WHERE id = ?", [$id]);
        if (!$schedule) {
            $this->abort(404, 'Schedule not found');
        }

        $reports = $db->fetchAll("SELECT id, report_code, report_name_en, report_name_ar FROM report_definitions WHERE is_active = 1 AND is_schedulable = 1 ORDER BY report_name_en");

        $this->view('schedules/edit', [
            'title' => lang('reports.edit_schedule'),
            'breadcrumbs' => [
                ['label' => lang('reports.reports'), 'url' => '/reports'],
                ['label' => lang('reports.scheduled_reports'), 'url' => '/reports/schedules'],
                ['label' => lang('common.edit')],
            ],
            'schedule' => $schedule,
            'reports'  => $reports,
        ]);
    }
}