<?php
class FiscalYearController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $years = $db->fetchAll("SELECT * FROM fiscal_years ORDER BY start_date DESC");
        $periods = [];
        foreach ($years as $y) {
            $periods[$y['id']] = $db->fetchAll("SELECT * FROM fiscal_periods WHERE fiscal_year_id=? ORDER BY period_number", [$y['id']]);
        }

        $this->view('fiscal-years/index', [
            'title' => lang('finance.fiscal_years'),
            'breadcrumbs' => [
                ['label' => lang('finance.title'), 'url' => '/finance/invoices'],
                ['label' => lang('finance.fiscal_years')],
            ],
            'years'   => $years,
            'periods' => $periods,
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $rows = $db->fetchAll("SELECT * FROM fiscal_years ORDER BY start_date DESC");
        $data = [];
        foreach ($rows as $row) {
            $periodCount = (int)$db->fetchColumn("SELECT COUNT(*) FROM fiscal_periods WHERE fiscal_year_id=?", [$row['id']]);
            $data[] = [
                'id'         => $row['id'],
                'year_code'  => e($row['year_code']),
                'name_en'    => e($row['name_en']),
                'start_date' => format_date($row['start_date']),
                'end_date'   => format_date($row['end_date']),
                'periods'    => $periodCount,
                'status'     => status_badge($row['status']),
            ];
        }
        $this->json(['draw' => 1, 'recordsTotal' => count($data), 'recordsFiltered' => count($data), 'data' => $data]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'CSRF'], 403); return; }

        $validator = new Validator($request->all(), [
            'year_code'  => 'required|string|max:20|unique:fiscal_years,year_code',
            'name_en'    => 'required|string|max:100',
            'name_ar'    => 'required|string|max:100',
            'start_date' => 'required|date',
            'end_date'   => 'required|date',
            'status'     => 'required|in:planning,open,closed,locked',
        ]);

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

        $id = $this->db()->insert('fiscal_years', $validator->validated());
        AuditLog::log('create', 'finance', 'fiscal_year', $id, "Created fiscal year");
        $this->json(['success' => true, 'message' => lang('common.success'), 'redirect' => '/finance/fiscal-years']);
    }

    public function update(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'CSRF'], 403); return; }

        $id = (int)$request->routeParam('id');
        $validator = new Validator($request->all(), [
            'name_en'    => 'required|string|max:100',
            'name_ar'    => 'required|string|max:100',
            'status'     => 'required|in:planning,open,closed,locked',
        ]);

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

        $this->db()->update('fiscal_years', $validator->validated(), 'id = ?', [$id]);
        AuditLog::log('update', 'finance', 'fiscal_year', $id, "Updated fiscal year");
        $this->json(['success' => true, 'message' => lang('common.success')]);
    }

    public function storePeriod(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'CSRF'], 403); return; }

        $yearId = (int)$request->routeParam('id');
        $validator = new Validator($request->all(), [
            'period_number' => 'required|integer|min:1|max:12',
            'name_en'       => 'required|string|max:100',
            'name_ar'       => 'required|string|max:100',
            'start_date'    => 'required|date',
            'end_date'      => 'required|date',
            'status'        => 'required|in:open,closed,locked',
        ]);

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

        $data = $validator->validated();
        $data['fiscal_year_id'] = $yearId;

        $id = $this->db()->insert('fiscal_periods', $data);
        AuditLog::log('create', 'finance', 'fiscal_period', $id, "Created fiscal period");
        $this->json(['success' => true, 'message' => lang('common.success')]);
    }
}