<?php

class InstallmentTemplateController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('installment-templates/index', [
            'title' => lang('adv_finance.installment_templates'),
            'breadcrumbs' => [
                ['label' => lang('adv_finance.title'), 'url' => '/advanced-finance/installments'],
                ['label' => lang('adv_finance.installment_templates')],
            ],
        ], 'app');
    }

    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'] ?? '';

        $where = '1=1';
        $params = [];
        if ($search) {
            $where .= ' AND (template_code LIKE ? OR name_en LIKE ? OR name_ar LIKE ?)';
            $like = "%{$search}%";
            $params = [$like, $like, $like];
        }

        $total = (int) $db->fetchColumn("SELECT COUNT(*) FROM installment_plan_templates");
        $filtered = (int) $db->fetchColumn("SELECT COUNT(*) FROM installment_plan_templates WHERE {$where}", $params);
        $rows = $db->fetchAll(
            "SELECT * FROM installment_plan_templates WHERE {$where} ORDER BY id DESC LIMIT {$length} OFFSET {$start}",
            $params
        );

        $data = [];
        foreach ($rows as $r) {
            $data[] = [
                'id'                     => $r['id'],
                'template_code'          => $r['template_code'],
                'name_en'                => $r['name_en'],
                'name_ar'                => $r['name_ar'],
                'number_of_installments' => $r['number_of_installments'],
                'frequency'              => $r['frequency'],
                'down_payment_pct'       => $r['down_payment_percentage'] . '%',
                'is_active'              => $r['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>',
            ];
        }

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

    public function create(Request $request): void
    {
        $this->view('installment-templates/form', [
            'title' => lang('common.create') . ' ' . lang('adv_finance.template'),
            'breadcrumbs' => [
                ['label' => lang('adv_finance.installment_templates'), 'url' => '/advanced-finance/installment-templates'],
                ['label' => lang('common.create')],
            ],
            'template' => null,
        ], 'app');
    }

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

        $validator = new Validator($request->all(), [
            'template_code'          => 'required|string|max:30|unique:installment_plan_templates,template_code',
            'name_en'                => 'required|string|max:200',
            'name_ar'                => 'required|string|max:200',
            'number_of_installments' => 'required|integer|min:1|max:120',
            'frequency'              => 'required|in:weekly,biweekly,monthly,bimonthly,quarterly,semi_annual,annual',
            'down_payment_percentage'=> 'required|decimal|min:0|max:100',
            'interest_rate'          => 'required|decimal|min:0|max:100',
            'late_payment_fee'       => 'required|decimal|min:0',
            'grace_days'             => 'required|integer|min:0',
            'is_active'              => 'nullable|boolean',
        ]);

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

        $d = $validator->validated();
        $d['is_active'] = isset($d['is_active']) ? 1 : 1;
        $id = $this->db()->insert('installment_plan_templates', $d);
        $this->audit('create', 'installment_plan_templates', $id, 'Created installment template ' . $d['template_code']);
        $this->json(['success' => true, 'message' => lang('adv_finance.saved'), 'redirect' => '/advanced-finance/installment-templates']);
    }

    public function edit(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        $template = $this->db()->fetchOne("SELECT * FROM installment_plan_templates WHERE id = ?", [$id]);
        if (!$template) { $this->abort(404, 'Not found'); return; }

        $this->view('installment-templates/form', [
            'title' => lang('common.edit') . ' ' . $template['template_code'],
            'breadcrumbs' => [
                ['label' => lang('adv_finance.installment_templates'), 'url' => '/advanced-finance/installment-templates'],
                ['label' => lang('common.edit')],
            ],
            'template' => $template,
        ], 'app');
    }

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

        $validator = new Validator($request->all(), [
            'template_code'          => "required|string|max:30|unique:installment_plan_templates,template_code,{$id}",
            'name_en'                => 'required|string|max:200',
            'name_ar'                => 'required|string|max:200',
            'number_of_installments' => 'required|integer|min:1|max:120',
            'frequency'              => 'required|in:weekly,biweekly,monthly,bimonthly,quarterly,semi_annual,annual',
            'down_payment_percentage'=> 'required|decimal|min:0|max:100',
            'interest_rate'          => 'required|decimal|min:0|max:100',
            'late_payment_fee'       => 'required|decimal|min:0',
            'grace_days'             => 'required|integer|min:0',
            'is_active'              => 'nullable|boolean',
        ]);

        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $d = $validator->validated();
        $d['is_active'] = !empty($d['is_active']) ? 1 : 0;

        $this->db()->update('installment_plan_templates', $d, 'id = ?', [$id]);
        $this->audit('update', 'installment_plan_templates', $id, 'Updated template');
        $this->json(['success' => true, 'message' => lang('adv_finance.saved'), 'redirect' => '/advanced-finance/installment-templates']);
    }

    public function delete(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $id = (int)$request->routeParam('id');
        $this->db()->update('installment_plan_templates', ['is_active' => 0], 'id = ?', [$id]);
        $this->audit('delete', 'installment_plan_templates', $id, 'Deactivated template');
        $this->json(['success' => true, 'message' => lang('adv_finance.deleted')]);
    }
}