<?php
require_once __DIR__ . '/BaseController.php';

class CarnetTypeController extends BaseController
{
    public function index(Request $request): void
    {
        $this->view('carnet-types/index', [
            'title' => lang('cards.carnet_types'),
            'breadcrumbs' => [['label' => lang('cards.carnets'), 'url' => '/carnets'], ['label' => lang('cards.carnet_types')]],
        ]);
    }

    public function datatable(Request $request): void
    {
        $baseQuery = "SELECT id, type_code, name_en, name_ar, max_entries, validity_days, price, is_active FROM carnet_types WHERE 1=1";
        $columns = [
            ['db' => 'id', 'searchable' => false], ['db' => 'type_code', 'searchable' => true],
            ['db' => 'name_en', 'searchable' => true], ['db' => 'max_entries', 'searchable' => false],
            ['db' => 'validity_days', 'searchable' => false], ['db' => 'price', 'searchable' => false],
            ['db' => 'is_active', 'searchable' => false],
        ];
        $this->handleDataTable($request, $baseQuery, [], $columns, 'id ASC');
    }

    public function create(Request $request): void
    {
        $this->view('carnet-types/form', [
            'title' => lang('cards.create_carnet_type'), 'carnetType' => null, 'formAction' => '/carnet-types',
            'breadcrumbs' => [['label' => lang('cards.carnets'), 'url' => '/carnets'], ['label' => lang('cards.carnet_types'), 'url' => '/carnet-types'], ['label' => lang('common.create')]],
        ]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $validator = new Validator($request->all(), [
            'type_code' => 'required|string|max:20|unique:carnet_types,type_code',
            'name_en' => 'required|string|max:200', 'name_ar' => 'required|string|max:200',
            'max_entries' => 'required|integer|min:1', 'price' => 'required|decimal|min:0',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['validity_days'] = $request->post('validity_days') ?: null;
        $data['is_transferable'] = $request->post('is_transferable') ? 1 : 0;
        $data['is_active'] = $request->post('is_active', 1) ? 1 : 0;
        $data['created_at'] = date('Y-m-d H:i:s');

        $db = Database::getInstance();
        $id = $db->insert('carnet_types', $data);
        AuditLog::log('create', 'cards', 'carnet_types', $id, "Carnet type created");
        $this->json(['success' => true, 'message' => lang('common.success'), 'redirect' => '/carnet-types']);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = Database::getInstance();
        $ct = $db->fetchOne("SELECT * FROM carnet_types WHERE id = ?", [$id]);
        if (!$ct) { $this->abort(404, 'Not found'); return; }
        $this->view('carnet-types/form', [
            'title' => lang('cards.edit_carnet_type'), 'carnetType' => $ct, 'formAction' => '/carnet-types/' . $id,
            'breadcrumbs' => [['label' => lang('cards.carnets'), 'url' => '/carnets'], ['label' => lang('cards.carnet_types'), 'url' => '/carnet-types'], ['label' => lang('common.edit')]],
        ]);
    }

    public function update(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $id = (int) $request->routeParam('id');
        $validator = new Validator($request->all(), [
            'type_code' => "required|string|max:20|unique:carnet_types,type_code,{$id}",
            'name_en' => 'required|string|max:200', 'name_ar' => 'required|string|max:200',
            'max_entries' => 'required|integer|min:1', 'price' => 'required|decimal|min:0',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['validity_days'] = $request->post('validity_days') ?: null;
        $data['is_transferable'] = $request->post('is_transferable') ? 1 : 0;
        $data['is_active'] = $request->post('is_active', 1) ? 1 : 0;

        $db = Database::getInstance();
        $db->update('carnet_types', $data, 'id = ?', [$id]);
        AuditLog::log('update', 'cards', 'carnet_types', $id, "Carnet type updated");
        $this->json(['success' => true, 'message' => lang('common.success'), 'redirect' => '/carnet-types']);
    }
}