<?php

namespace App\Models;

use CodeIgniter\Model;

class TipSaleModel extends Model
{
    protected $table = 'tip_sales';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'tip_id',
        'author',
        'msisdn',
        'amount',
        'created_at',
        'tag',
        'is_settled',
        'settled_at',
        'settled_by',
        'settlement_notes',
    ];
    
    // Get unsettled sales for an author
    public function getUnsettledSales($author = null, $days = 7)
    {
        $this->where('is_settled', 0);
        
        if ($author) {
            $this->where('author', $author);
        }
        
        if ($days) {
            $dateLimit = date('Y-m-d H:i:s', strtotime("-{$days} days"));
            $this->where('created_at >=', $dateLimit);
        }
        
        return $this->findAll();
    }
    
    // Get settled sales for an author
    public function getSettledSales($author = null, $days = 30)
    {
        $this->where('is_settled', 1);
        
        if ($author) {
            $this->where('author', $author);
        }
        
        if ($days) {
            $dateLimit = date('Y-m-d H:i:s', strtotime("-{$days} days"));
            $this->where('settled_at >=', $dateLimit);
        }
        
        return $this->findAll();
    }
    
    // Mark sales as settled
    public function markAsSettled($saleIds, $settledBy, $notes = null)
    {
        $data = [
            'is_settled' => 1,
            'settled_at' => date('Y-m-d H:i:s'),
            'settled_by' => $settledBy,
            'settlement_notes' => $notes
        ];
        
        return $this->whereIn('id', $saleIds)->set($data)->update();
    }
    
    // Get settlement summary for an author
    public function getSettlementSummary($author, $days = 7)
    {
        $dateLimit = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        
        // Get total sales count and amount
        $totalSales = $this->where('author', $author)
                          ->where('created_at >=', $dateLimit)
                          ->countAllResults();
        
        $totalAmount = $this->where('author', $author)
                           ->where('created_at >=', $dateLimit)
                           ->selectSum('amount')
                           ->get()
                           ->getRow()
                           ->amount ?? 0;
        
        // Get settled sales count and amount
        $settledCount = $this->where('author', $author)
                            ->where('created_at >=', $dateLimit)
                            ->where('is_settled', 1)
                            ->countAllResults();
        
        $settledAmount = $this->where('author', $author)
                             ->where('created_at >=', $dateLimit)
                             ->where('is_settled', 1)
                             ->selectSum('amount')
                             ->get()
                             ->getRow()
                             ->amount ?? 0;
        
        // Calculate unsettled
        $unsettledCount = $totalSales - $settledCount;
        $unsettledAmount = $totalAmount - $settledAmount;
        
        return [
            'total_sales' => $totalSales,
            'total_amount' => $totalAmount,
            'settled_count' => $settledCount,
            'settled_amount' => $settledAmount,
            'unsettled_count' => $unsettledCount,
            'unsettled_amount' => $unsettledAmount
        ];
    }
    
    // Get unsettled sales for settlement (FIFO order)
    public function getUnsettledSalesForSettlement($author, $targetAmount, $days = 7)
    {
        $dateLimit = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        
        // Get unsettled sales ordered by created_at ASC (oldest first - FIFO)
        $sales = $this->where('author', $author)
                      ->where('is_settled', 0)
                      ->where('created_at >=', $dateLimit)
                      ->orderBy('created_at', 'ASC')
                      ->findAll();
        
        // Select sales until cumulative amount >= targetAmount
        $selectedSales = [];
        $cumulativeAmount = 0;
        
        foreach ($sales as $sale) {
            $selectedSales[] = $sale;
            $cumulativeAmount += (float) $sale['amount'];
            
            if ($cumulativeAmount >= $targetAmount) {
                break;
            }
        }
        
        return $selectedSales;
    }
} 