<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

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

class PricingController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();

        $facilities = $db->select(
            "SELECT f.id, f.code, f.name_ar, f.facility_type,
                    COUNT(DISTINCT fu.id) as unit_count,
                    COUNT(DISTINCT pr.id) as rule_count
             FROM sa_facilities f
             LEFT JOIN sa_facility_units fu ON fu.facility_id = f.id AND fu.is_active = 1
             LEFT JOIN sa_pricing_rules pr ON pr.facility_unit_id = fu.id AND pr.is_active = 1
             WHERE f.is_archived = 0 AND f.is_active = 1
             GROUP BY f.id
             ORDER BY f.name_ar",
            []
        );

        return $this->view('SportsActivity.Views.pricing.index', [
            'facilities' => $facilities,
        ]);
    }

    public function rules(Request $request): Response
    {
        $db = App::getInstance()->db();
        $unitId = (int) $request->get('unit_id', 0);
        $facilityId = (int) $request->get('facility_id', 0);

        if ($facilityId > 0) {
            $facility = $db->selectOne("SELECT * FROM sa_facilities WHERE id = ? AND is_archived = 0", [$facilityId]);
            if (!$facility) {
                return $this->redirect('/sa/pricing')->withError('المرفق غير موجود');
            }

            $units = $db->select(
                "SELECT * FROM sa_facility_units WHERE facility_id = ? AND is_active = 1 ORDER BY sort_order",
                [$facilityId]
            );
            $brackets = $db->select(
                "SELECT * FROM sa_time_brackets WHERE facility_id = ? AND is_active = 1 ORDER BY start_time",
                [$facilityId]
            );
        } else {
            $facility = null;
            $units = [];
            $brackets = [];
        }

        $rules = [];
        if ($unitId > 0) {
            $rules = $db->select(
                "SELECT pr.*, tb.name_ar as bracket_name, tb.bracket_type, tb.start_time as bracket_start, tb.end_time as bracket_end
                 FROM sa_pricing_rules pr
                 JOIN sa_time_brackets tb ON tb.id = pr.time_bracket_id
                 WHERE pr.facility_unit_id = ? AND pr.is_active = 1
                 ORDER BY tb.start_time, pr.group_size_min",
                [$unitId]
            );
        }

        $allFacilities = $db->select(
            "SELECT id, name_ar FROM sa_facilities WHERE is_archived = 0 AND is_active = 1 ORDER BY name_ar",
            []
        );

        return $this->view('SportsActivity.Views.pricing.rules', [
            'facility'      => $facility,
            'facilities'    => $allFacilities,
            'units'         => $units,
            'brackets'      => $brackets,
            'rules'         => $rules,
            'selectedUnit'  => $unitId,
            'selectedFacility' => $facilityId,
        ]);
    }

    public function storeRule(Request $request): Response
    {
        $db = App::getInstance()->db();

        $data = [
            'facility_unit_id'          => (int) $request->post('facility_unit_id', 0),
            'time_bracket_id'           => (int) $request->post('time_bracket_id', 0),
            'group_size_min'            => (int) $request->post('group_size_min', 1),
            'group_size_max'            => (int) $request->post('group_size_max', 1),
            'price_per_person_member'   => $request->post('price_per_person_member', '0'),
            'price_per_person_nonmember' => $request->post('price_per_person_nonmember', '0'),
            'effective_from'            => $request->post('effective_from', ''),
            'effective_to'              => $request->post('effective_to', '') ?: null,
        ];

        $errors = [];
        if ($data['facility_unit_id'] <= 0) $errors[] = 'الوحدة مطلوبة';
        if ($data['time_bracket_id'] <= 0) $errors[] = 'الفترة الزمنية مطلوبة';
        if ($data['group_size_min'] < 1) $errors[] = 'الحد الأدنى للمجموعة يجب أن يكون 1 على الأقل';
        if ($data['group_size_max'] < $data['group_size_min']) $errors[] = 'الحد الأقصى يجب أن يكون أكبر أو يساوي الحد الأدنى';
        if ($data['facility_unit_id'] > 0) {
            $unitCap = $db->selectOne("SELECT max_capacity FROM sa_facility_units WHERE id = ?", [$data['facility_unit_id']]);
            if ($unitCap && (int) $unitCap['max_capacity'] > 0 && $data['group_size_max'] > (int) $unitCap['max_capacity']) {
                $errors[] = 'الحد الأقصى للمجموعة (' . $data['group_size_max'] . ') يتجاوز سعة الوحدة (' . $unitCap['max_capacity'] . ')';
            }
        }
        if ((float) $data['price_per_person_member'] <= 0) $errors[] = 'سعر العضو مطلوب';
        if ((float) $data['price_per_person_nonmember'] <= 0) $errors[] = 'سعر غير العضو مطلوب';
        if ($data['effective_from'] === '') $errors[] = 'تاريخ البداية مطلوب';

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
            $session->flash('_old_input', $request->all());

            $unit = $db->selectOne("SELECT facility_id FROM sa_facility_units WHERE id = ?", [$data['facility_unit_id']]);
            $facilityId = $unit ? (int) $unit['facility_id'] : 0;
            return $this->redirect("/sa/pricing/rules?facility_id={$facilityId}&unit_id={$data['facility_unit_id']}");
        }

        $data['is_active'] = 1;
        $data['created_by'] = (int) (App::getInstance()->session()->get('employee_id') ?? 0);
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');

        $db->insert('sa_pricing_rules', $data);

        $unit = $db->selectOne("SELECT facility_id FROM sa_facility_units WHERE id = ?", [$data['facility_unit_id']]);
        $facilityId = $unit ? (int) $unit['facility_id'] : 0;

        return $this->redirect("/sa/pricing/rules?facility_id={$facilityId}&unit_id={$data['facility_unit_id']}")
            ->withSuccess('تم إضافة قاعدة التسعير');
    }

    public function updateRule(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $rule = $db->selectOne("SELECT * FROM sa_pricing_rules WHERE id = ?", [(int) $id]);

        if (!$rule) {
            return $this->redirect('/sa/pricing')->withError('القاعدة غير موجودة');
        }

        $update = [
            'group_size_min'             => (int) $request->post('group_size_min', $rule['group_size_min']),
            'group_size_max'             => (int) $request->post('group_size_max', $rule['group_size_max']),
            'price_per_person_member'    => $request->post('price_per_person_member', $rule['price_per_person_member']),
            'price_per_person_nonmember' => $request->post('price_per_person_nonmember', $rule['price_per_person_nonmember']),
            'effective_from'             => $request->post('effective_from', $rule['effective_from']),
            'effective_to'               => $request->post('effective_to', '') ?: null,
            'updated_at'                 => date('Y-m-d H:i:s'),
        ];

        $db->update('sa_pricing_rules', $update, 'id = ?', [(int) $id]);

        $facilityId = 0;
        $unit = $db->selectOne("SELECT facility_id FROM sa_facility_units WHERE id = ?", [(int) $rule['facility_unit_id']]);
        if ($unit) $facilityId = (int) $unit['facility_id'];

        return $this->redirect("/sa/pricing/rules?facility_id={$facilityId}&unit_id={$rule['facility_unit_id']}")
            ->withSuccess('تم تحديث القاعدة');
    }

    public function deactivateRule(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $rule = $db->selectOne("SELECT * FROM sa_pricing_rules WHERE id = ?", [(int) $id]);

        if (!$rule) {
            return $this->redirect('/sa/pricing')->withError('القاعدة غير موجودة');
        }

        $db->update('sa_pricing_rules', ['is_active' => 0, 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [(int) $id]);

        $facilityId = 0;
        $unit = $db->selectOne("SELECT facility_id FROM sa_facility_units WHERE id = ?", [(int) $rule['facility_unit_id']]);
        if ($unit) $facilityId = (int) $unit['facility_id'];

        return $this->redirect("/sa/pricing/rules?facility_id={$facilityId}&unit_id={$rule['facility_unit_id']}")
            ->withSuccess('تم تعطيل القاعدة');
    }
}
