<?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;

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

        $reps = $db->select(
            "SELECT sr.*, e.full_name_ar as employee_name,
                    (SELECT COUNT(*) FROM sales_commissions WHERE representative_id = sr.id) as total_sales,
                    (SELECT COALESCE(SUM(commission_amount), 0) FROM sales_commissions WHERE representative_id = sr.id) as total_commission
             FROM sales_representatives sr
             LEFT JOIN employees e ON e.id = sr.employee_id
             ORDER BY sr.name_ar"
        );

        return $this->view('Sales.Views.commissions.representatives', ['reps' => $reps]);
    }

    public function createRep(Request $request): Response
    {
        $this->authorize('sales.commission.manage');
        $db = App::getInstance()->db();

        $employees = $db->select("SELECT id, full_name_ar FROM employees WHERE is_archived = 0 ORDER BY full_name_ar");

        return $this->view('Sales.Views.commissions.rep_form', ['rep' => null, 'employees' => $employees]);
    }

    public function storeRep(Request $request): Response
    {
        $this->authorize('sales.commission.manage');
        $db = App::getInstance()->db();

        $db->insert('sales_representatives', [
            'employee_id' => $request->post('employee_id') ?: null,
            'code' => $request->post('code'),
            'name_ar' => $request->post('name_ar'),
            'name_en' => $request->post('name_en'),
            'phone' => $request->post('phone'),
            'email' => $request->post('email'),
            'commission_type' => $request->post('commission_type', 'percentage'),
            'commission_rate' => $request->post('commission_rate', '0'),
            'target_amount' => $request->post('target_amount') ?: null,
        ]);

        return $this->redirect('/sales/commissions/representatives')->withSuccess('تم إضافة مندوب المبيعات');
    }

    public function report(Request $request): Response
    {
        $this->authorize('sales.commission.view');
        $db = App::getInstance()->db();

        $month = $request->get('month', date('Y-m'));
        $repId = (int) $request->get('representative_id', 0);

        $where = "DATE_FORMAT(sc.period_month, '%Y-%m') = ?";
        $params = [$month];

        if ($repId) {
            $where .= ' AND sc.representative_id = ?';
            $params[] = $repId;
        }

        $commissions = $db->select(
            "SELECT sc.*, sr.name_ar as rep_name, sr.code as rep_code
             FROM sales_commissions sc
             JOIN sales_representatives sr ON sr.id = sc.representative_id
             WHERE {$where}
             ORDER BY sr.name_ar, sc.created_at DESC",
            $params
        );

        $summary = $db->select(
            "SELECT sr.id, sr.name_ar, sr.code, sr.commission_rate, sr.target_amount,
                    COUNT(sc.id) as sale_count,
                    COALESCE(SUM(sc.sale_amount), 0) as total_sales,
                    COALESCE(SUM(sc.commission_amount), 0) as total_commission
             FROM sales_representatives sr
             LEFT JOIN sales_commissions sc ON sc.representative_id = sr.id AND DATE_FORMAT(sc.period_month, '%Y-%m') = ?
             WHERE sr.is_active = 1
             GROUP BY sr.id
             ORDER BY total_sales DESC",
            [$month]
        );

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

        return $this->view('Sales.Views.commissions.report', [
            'commissions' => $commissions,
            'summary' => $summary,
            'reps' => $reps,
            'month' => $month,
            'representative_id' => $repId,
        ]);
    }

    public function customerPricing(Request $request): Response
    {
        $this->authorize('sales.pricing.view');
        $db = App::getInstance()->db();

        $prices = $db->select(
            "SELECT cp.*, i.name_ar as item_name, m.full_name_ar as member_name, pl.name_ar as list_name
             FROM customer_item_prices cp
             LEFT JOIN inventory_items i ON i.id = cp.item_id
             LEFT JOIN members m ON m.id = cp.member_id
             LEFT JOIN customer_price_lists pl ON pl.id = cp.price_list_id
             WHERE cp.is_active = 1
             ORDER BY cp.created_at DESC
             LIMIT 200"
        );

        return $this->view('Sales.Views.commissions.customer_pricing', ['prices' => $prices]);
    }
}
