<?php

namespace Modules\Loyalty\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Security;

class LoyaltyController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index(): void
    {
        $this->requirePermission('loyalty_points_view');

        $db = Database::getInstance();
        $customerId = $this->request->get('customer_id', '');
        $type = $this->request->get('type', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;

        $query = $db->table('loyalty_points lp')
            ->select('lp.*, c.first_name, c.last_name, c.phone')
            ->leftJoin('customers c', 'lp.customer_id', '=', 'c.id');

        if (!empty($customerId)) {
            $query->where('lp.customer_id', $customerId);
        }

        if (!empty($type)) {
            $query->where('lp.type', $type);
        }

        $points = $query->orderBy('lp.created_at', 'DESC')->paginate($perPage, $page);

        $customers = $db->table('customers')
            ->where('deleted_at', 'IS', null)
            ->orderBy('first_name', 'ASC')
            ->get();

        $this->view('Loyalty/loyalty/index', [
            'title' => 'Loyalty Points',
            'breadcrumb' => ['Loyalty Points' => url('loyalty')],
            'points' => $points,
            'customers' => $customers,
            'customerId' => $customerId,
            'type' => $type,
        ]);
    }

    public function rules(): void
    {
        $this->requirePermission('loyalty_rules_view');

        $db = Database::getInstance();
        $rules = $db->table('loyalty_rules')
            ->orderBy('created_at', 'DESC')
            ->get();

        $this->view('Loyalty/loyalty/rules', [
            'title' => 'Loyalty Rules',
            'breadcrumb' => [
                'Loyalty Points' => url('loyalty'),
                'Rules' => url('loyalty/rules'),
            ],
            'rules' => $rules,
        ]);
    }

    public function storeRule(): void
    {
        $this->requirePermission('loyalty_rules_manage');

        $validated = $this->validate([
            'name' => 'required|max_length:100',
            'type' => 'required|in:earning,redeeming',
            'points_per_amount' => 'required|numeric|min:0',
            'amount_required' => 'required|numeric|min:0',
            'max_points' => 'integer|min:0',
            'is_active' => 'in:0,1',
        ]);

        $validated['is_active'] = $validated['is_active'] ?? 1;
        $validated['points_per_amount'] = (float)$validated['points_per_amount'];
        $validated['amount_required'] = (float)$validated['amount_required'];
        $validated['max_points'] = !empty($validated['max_points']) ? (int)$validated['max_points'] : 0;

        $id = $this->request->post('id');

        if (!empty($id)) {
            $existing = Database::getInstance()->table('loyalty_rules')->find($id);
            if (!$existing) {
                $this->redirectWith(url('loyalty/rules'), 'error', 'Rule not found.');
            }
            $oldValues = (array)$existing;
            Database::getInstance()->table('loyalty_rules')->where('id', $id)->update($validated);
            $this->logAudit('update', 'loyalty_rules', $id, $oldValues, $validated);
            $msg = 'Rule updated successfully.';
        } else {
            $id = Database::getInstance()->table('loyalty_rules')->insert($validated);
            $this->logAudit('create', 'loyalty_rules', $id, null, $validated);
            $msg = 'Rule created successfully.';
        }

        $this->logActivity('manage_rule', $msg . ': ' . $validated['name']);
        $this->redirectWith(url('loyalty/rules'), 'success', $msg);
    }
}
