<?php

class ScheduleApiController extends Controller
{
    public function datatable(Request $request): void
    {
        $db = $this->db();

        $draw   = (int) $request->get('draw', 1);
        $start  = (int) $request->get('start', 0);
        $length = (int) $request->get('length', 25);
        $search = $request->get('search', [])['value'] ?? '';

        $baseSql = "SELECT rs.*, rd.report_name_en, rd.report_name_ar, rd.report_code
                    FROM report_schedules rs
                    JOIN report_definitions rd ON rs.report_id = rd.id";

        $total = (int) $db->fetchColumn("SELECT COUNT(*) FROM report_schedules");

        $where = [];
        $params = [];
        if ($search) {
            $where[] = "(rs.schedule_name LIKE ? OR rd.report_name_en LIKE ? OR rd.report_code LIKE ?)";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
        }

        $whereStr = !empty($where) ? ' WHERE ' . implode(' AND ', $where) : '';
        $filtered = (int) $db->fetchColumn("SELECT COUNT(*) FROM report_schedules rs JOIN report_definitions rd ON rs.report_id = rd.id" . $whereStr, $params);

        $orderCol = (int) ($request->get('order', [])['0']['column'] ?? 0);
        $orderDir = strtoupper($request->get('order', [])['0']['dir'] ?? 'DESC') === 'ASC' ? 'ASC' : 'DESC';
        $orderMap = ['rs.id', 'rs.schedule_name', 'rd.report_name_en', 'rs.frequency', 'rs.is_active', 'rs.last_run_at', 'rs.next_run_at'];
        $orderField = $orderMap[$orderCol] ?? 'rs.id';

        $sql = $baseSql . $whereStr . " ORDER BY {$orderField} {$orderDir} LIMIT " . (int)$length . " OFFSET " . (int)$start;
        $rows = $db->fetchAll($sql, $params);

        $this->json([
            'draw'            => $draw,
            'recordsTotal'    => $total,
            'recordsFiltered' => $filtered,
            'data'            => $rows,
        ]);
    }

    public function store(Request $request): void
    {
        $db = $this->db();

        $validator = new Validator($request->all(), [
            'report_id'       => 'required|integer',
            'schedule_name'   => 'required|string|max:200',
            'frequency'       => 'required|in:daily,weekly,monthly,quarterly,yearly',
            'day_of_week'     => 'nullable|integer',
            'day_of_month'    => 'nullable|integer',
            'time_of_day'     => 'required|string',
            'output_format'   => 'required|in:pdf,excel,csv,word',
            'delivery_method' => 'required|in:email,in_app,save,both_email_save',
            'recipients'      => 'nullable|string',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $data = $validator->validated();
        $data['created_by'] = Auth::id();
        $data['is_active'] = 1;
        $data['recipients'] = $data['recipients'] ? json_encode(array_map('trim', explode(',', $data['recipients']))) : null;

        $id = $db->insert('report_schedules', $data);
        $this->audit('create', 'report_schedules', $id, 'Created report schedule');
        $this->json(['success' => true, 'message' => lang('reports.schedule_created'), 'id' => $id]);
    }

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

        $schedule = $db->fetchOne("SELECT * FROM report_schedules WHERE id = ?", [$id]);
        if (!$schedule) {
            $this->json(['success' => false, 'message' => 'Not found'], 404);
            return;
        }

        $validator = new Validator($request->all(), [
            'report_id'       => 'required|integer',
            'schedule_name'   => 'required|string|max:200',
            'frequency'       => 'required|in:daily,weekly,monthly,quarterly,yearly',
            'day_of_week'     => 'nullable|integer',
            'day_of_month'    => 'nullable|integer',
            'time_of_day'     => 'required|string',
            'output_format'   => 'required|in:pdf,excel,csv,word',
            'delivery_method' => 'required|in:email,in_app,save,both_email_save',
            'recipients'      => 'nullable|string',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $data = $validator->validated();
        $data['recipients'] = $data['recipients'] ? json_encode(array_map('trim', explode(',', $data['recipients']))) : null;

        $db->update('report_schedules', $data, 'id = ?', [$id]);
        $this->audit('update', 'report_schedules', $id, 'Updated report schedule');
        $this->json(['success' => true, 'message' => lang('reports.schedule_updated')]);
    }

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

        $db->delete('report_schedule_runs', 'schedule_id = ?', [$id]);
        $db->delete('report_schedules', 'id = ?', [$id]);
        $this->audit('delete', 'report_schedules', $id, 'Deleted report schedule');
        $this->json(['success' => true, 'message' => lang('reports.schedule_deleted')]);
    }

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

        $schedule = $db->fetchOne("SELECT is_active FROM report_schedules WHERE id = ?", [$id]);
        if (!$schedule) {
            $this->json(['success' => false, 'message' => 'Not found'], 404);
            return;
        }

        $newState = $schedule['is_active'] ? 0 : 1;
        $db->update('report_schedules', ['is_active' => $newState], 'id = ?', [$id]);
        $this->json(['success' => true, 'message' => $newState ? 'Enabled' : 'Disabled']);
    }

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

        $runs = $db->fetchAll(
            "SELECT * FROM report_schedule_runs WHERE schedule_id = ? ORDER BY run_at DESC LIMIT 50",
            [$id]
        );

        $this->json(['success' => true, 'data' => $runs]);
    }
}