<?php

namespace App\Models;

use CodeIgniter\Model;

class AdditionalChargeModel extends Model
{
    protected $table         = 'additional_charges';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = [
        'parent_id',
        'invoice_id',
        'school_year',
        'semester',
        'charge_type',
        'title',
        'description',
        'amount',
        'due_date',
        'status',
        'created_by',
    ];

    protected $validationRules = [
        'parent_id'   => 'permit_empty|integer',
        'invoice_id'  => 'permit_empty|integer',
        'school_year' => 'required|string|max_length[20]',
        'semester'    => 'required|string|max_length[20]',
        'charge_type' => 'required|in_list[add,deduct]',
        'title'       => 'required|string|min_length[2]|max_length[255]',
        'description' => 'permit_empty|string',
        'amount'      => 'required|decimal',
        'due_date'    => 'permit_empty|valid_date',
        'status'      => 'required|in_list[pending,applied,voided]',
        'created_by'  => 'permit_empty|integer',
    ];

    public function byParentTerm(int $parentId, string $year, string $sem, ?string $status = null): array
    {
        $b = $this->where('parent_id', $parentId)
            ->where('school_year', $year)
            ->where('semester', $sem);
        if ($status !== null) $b->where('status', $status);
        return $b->orderBy('id', 'DESC')->findAll();
    }



    public function markApplied($ids, int $invoiceId): bool
    {
        $ids = is_array($ids) ? $ids : [$ids];
        if (!$ids) return true;
        return (bool) $this->whereIn('id', array_map('intval', $ids))
            ->set(['status' => 'applied', 'invoice_id' => $invoiceId])
            ->update();
    }



    public function listAllForTerm(
        string $schoolYear,
        string $semester,
        ?string $status = null,
        ?string $q = null,
        int $perPage = 50,
        bool $fallbackToYear = true
    ) {
        // Helper to build the query with optional semester filter
        $build = function (?string $semFilter) use ($schoolYear, $status, $q) {
            $b = $this->select(
                "additional_charges.*,
                 CONCAT(COALESCE(users.lastname, ''), ', ', COALESCE(users.firstname, '')) AS parent_name,
                 invoices.invoice_number"
            )
                ->join('users', 'users.id = additional_charges.parent_id', 'left')
                ->join('invoices', 'invoices.id = additional_charges.invoice_id', 'left')
                ->where('additional_charges.school_year', $schoolYear);

            if ($semFilter !== null && $semFilter !== '') {
                $b->where('additional_charges.semester', $semFilter);
            }

            if (!empty($status)) {
                $b->where('additional_charges.status', $status);
            }

            if (!empty($q)) {
                $b->groupStart()
                    ->like('additional_charges.title', $q)
                    ->orLike('additional_charges.description', $q)
                    ->orLike('users.firstname', $q)
                    ->orLike('users.lastname', $q)
                    ->orLike('invoices.invoice_number', $q)
                    ->groupEnd();
            }

            return $b;
        };

        // First attempt: year + semester
        $result = $build($semester)->orderBy('additional_charges.id', 'DESC')->paginate($perPage);

        // Fallback: if no rows for this semester and allowed, retry year-only (helps when Spring data isn't entered yet)
        if ($fallbackToYear && empty($result) && $semester !== '') {
            $result = $build(null)->orderBy('additional_charges.id', 'DESC')->paginate($perPage);
        }

        return $result;
    }



}
