<?php
declare(strict_types=1);

namespace App\Modules\Sales\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\Pagination;

class ReferralController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('sales.referral.view');
        $db = App::getInstance()->db();

        $repFilter = trim((string) $request->get('rep_id', ''));
        $dateFrom = trim((string) $request->get('date_from', ''));
        $dateTo = trim((string) $request->get('date_to', ''));
        $statusFilter = trim((string) $request->get('status', ''));
        $page = max(1, (int) $request->get('page', 1));
        $perPage = 25;

        $where = '1=1';
        $params = [];

        if ($repFilter !== '') {
            $where .= ' AND mrc.representative_id = ?';
            $params[] = (int) $repFilter;
        }
        if ($dateFrom !== '') {
            $where .= ' AND mrc.commission_date >= ?';
            $params[] = $dateFrom;
        }
        if ($dateTo !== '') {
            $where .= ' AND mrc.commission_date <= ?';
            $params[] = $dateTo;
        }
        if ($statusFilter !== '') {
            $where .= ' AND mrc.status = ?';
            $params[] = $statusFilter;
        }

        $total = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM member_referral_commissions mrc WHERE {$where}",
            $params
        )['cnt'] ?? 0);

        $pagination = Pagination::paginate($total, $perPage, $page);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT mrc.*, sr.name_ar as rep_name, sr.code as rep_code, m.full_name_ar as member_name, m.membership_number
             FROM member_referral_commissions mrc
             LEFT JOIN sales_representatives sr ON sr.id = mrc.representative_id
             LEFT JOIN members m ON m.id = mrc.member_id
             WHERE {$where}
             ORDER BY mrc.commission_date DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        $reps = $db->select("SELECT id, code, name_ar FROM sales_representatives WHERE is_active = 1 ORDER BY name_ar", []);

        $totals = $db->selectOne(
            "SELECT COUNT(*) as total_count, COALESCE(SUM(commission_amount), 0) as total_amount FROM member_referral_commissions mrc WHERE {$where}",
            $params
        );

        return $this->view('Sales.Views.referrals.index', [
            'rows'       => $rows,
            'pagination' => $pagination,
            'reps'       => $reps,
            'filters'    => ['rep_id' => $repFilter, 'date_from' => $dateFrom, 'date_to' => $dateTo, 'status' => $statusFilter],
            'totals'     => $totals,
        ]);
    }
}
