<?php

namespace App\Models;

use CodeIgniter\Model;

class MemberPointModel extends Model
{
    protected $table = 'member_points';
    protected $primaryKey = 'id';
    protected $allowedFields = ['member_id', 'type', 'points', 'note', 'transaction_id', 'created_at'];
    protected $useTimestamps = false;

    public function getHistory(array $filters = []): array
    {
        $builder = $this->builder();
        $builder->select('member_points.*, members.name as member_name')
            ->join('members', 'members.id = member_points.member_id');

        if (!empty($filters['member_id'])) {
            $builder->where('member_points.member_id', $filters['member_id']);
        }

        return $builder->orderBy('member_points.id', 'DESC')->get()->getResultArray();
    }

    public function sumRedeemedPointsForFilters(array $filters = []): int
    {
        $builder = $this->builder();
        $builder->selectSum('member_points.points', 'points')->where('member_points.type', 'redeem');

        if (!empty($filters['barber']) || !empty($filters['payment_method'])) {
            $builder->join('transactions', 'transactions.id = member_points.transaction_id');
            if (!empty($filters['barber'])) {
                $builder->where('transactions.barber', $filters['barber']);
            }
            if (!empty($filters['payment_method'])) {
                $builder->where('transactions.payment_method', $filters['payment_method']);
            }
        }

        if (!empty($filters['date_from'])) {
            $builder->where('member_points.created_at >=', $filters['date_from'] . ' 00:00:00');
        }
        if (!empty($filters['date_to'])) {
            $builder->where('member_points.created_at <=', $filters['date_to'] . ' 23:59:59');
        }

        $result = $builder->get()->getRowArray();

        return (int) ($result['points'] ?? 0);
    }

    public function getPointsByTransactionIds(array $transactionIds, string $type): array
    {
        if (empty($transactionIds)) {
            return [];
        }

        $rows = $this->select('transaction_id, points')
            ->where('type', $type)
            ->whereIn('transaction_id', $transactionIds)
            ->findAll();

        $map = [];
        foreach ($rows as $row) {
            $map[(int) $row['transaction_id']] = (int) $row['points'];
        }

        return $map;
    }

    public function addEntry(int $memberId, string $type, int $points, string $note, ?int $transactionId = null): void
    {
        $this->insert([
            'member_id' => $memberId,
            'type' => $type,
            'points' => $points,
            'note' => $note,
            'transaction_id' => $transactionId,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        $memberModel = new MemberModel();
        $member = $memberModel->find($memberId);
        if ($member) {
            $delta = $type === 'redeem' ? -$points : $points;
            $memberModel->update($memberId, ['points' => max(0, (int) $member['points'] + $delta)]);
        }
    }

    public function deleteEntry(int $id): bool
    {
        $entry = $this->find($id);
        if (!$entry) {
            return false;
        }

        $memberModel = new MemberModel();
        $member = $memberModel->find($entry['member_id']);
        if ($member) {
            $delta = $entry['type'] === 'redeem' ? (int) $entry['points'] : -(int) $entry['points'];
            $memberModel->update($entry['member_id'], ['points' => max(0, (int) $member['points'] + $delta)]);
        }

        return (bool) $this->delete($id);
    }
}
