<?php

namespace App\Models;

use CodeIgniter\Model;

class CompanyModel extends Model
{
    protected $table = 'companies';
    protected $primaryKey = 'id';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'name', 'logo', 'invoice_header_note', 'invoice_footer_note', 'base_currency', 'tax_number', 'address',
        'phone', 'email', 'owner_user_id', 'notify_before_days_default', 'is_active',
        'slug', 'is_site_enabled', 'site_primary_color', 'site_font', 'site_tagline',
        'site_about_text', 'site_vision', 'site_mission', 'site_services_text', 'site_footer_text',
        'site_facebook_url', 'site_twitter_url', 'site_instagram_url', 'site_whatsapp_number',
    ];

    public function findBySlug(string $slug): ?array
    {
        return $this->where('slug', $slug)->where('is_site_enabled', 1)->first();
    }

    /** توليد slug فريد من اسم الشركة (عربي/إنجليزي) */
    public function generateSlug(string $name, ?int $ignoreId = null): string
    {
        $base = url_title(strtolower($name), '-', true);
        if (! $base) {
            $base = 'company-' . time();
        }

        $slug = $base;
        $i = 1;
        while (true) {
            $query = $this->where('slug', $slug);
            if ($ignoreId) $query->where('id !=', $ignoreId);
            if (! $query->first()) break;
            $slug = $base . '-' . (++$i);
        }

        return $slug;
    }

    /**
     * تقرير الأرباح والخسائر لفترة معينة
     */
    public function profitAndLoss(int $companyId, ?string $from = null, ?string $to = null): array
    {
        $invoiceModel = new InvoiceModel();
        $expenseModel = new ExpenseModel();

        $revenueQuery = $invoiceModel->where('company_id', $companyId)->where('status', 'paid');
        if ($from) $revenueQuery->where('paid_at >=', $from);
        if ($to) $revenueQuery->where('paid_at <=', $to);
        $revenue = (float) ($revenueQuery->selectSum('amount')->first()['amount'] ?? 0);

        $expenseQuery = $expenseModel->where('company_id', $companyId);
        if ($from) $expenseQuery->where('date >=', $from);
        if ($to) $expenseQuery->where('date <=', $to);
        $expenses = (float) ($expenseQuery->selectSum('amount')->first()['amount'] ?? 0);

        return [
            'revenue' => $revenue,
            'expenses' => $expenses,
            'net_profit' => $revenue - $expenses,
        ];
    }
}
