<?php

namespace Modules\Loyalty\Controllers;

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

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

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

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

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

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

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

        $this->view('Loyalty/gift_cards/index', [
            'title' => 'Gift Cards',
            'breadcrumb' => ['Gift Cards' => url('gift-cards')],
            'cards' => $cards,
            'status' => $status,
        ]);
    }

    public function create(): void
    {
        $this->requirePermission('loyalty_giftcards_create');

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

        $this->view('Loyalty/gift_cards/create', [
            'title' => 'Create Gift Card',
            'breadcrumb' => [
                'Gift Cards' => url('gift-cards'),
                'Create' => url('gift-cards/create'),
            ],
            'customers' => $customers,
        ]);
    }

    public function store(): void
    {
        $this->requirePermission('loyalty_giftcards_create');

        $validated = $this->validate([
            'customer_id' => 'required|integer',
            'initial_balance' => 'required|numeric|min:0',
            'expiry_date' => 'required|date',
        ]);

        $validated['card_number'] = 'GC-' . strtoupper(bin2hex(random_bytes(8)));
        $validated['current_balance'] = (float)$validated['initial_balance'];
        $validated['issue_date'] = date('Y-m-d');
        $validated['status'] = 'active';

        $cardId = Database::getInstance()->table('gift_cards')->insert($validated);
        $this->logActivity('create', 'Created gift card: ' . $validated['card_number']);
        $this->logAudit('create', 'gift_cards', $cardId, null, $validated);

        $this->redirectWith(url('gift-cards'), 'success', 'Gift card created successfully.');
    }

    public function reload(int $id): void
    {
        $this->requirePermission('loyalty_giftcards_reload');

        $db = Database::getInstance();
        $card = $db->table('gift_cards')->find($id);
        if (!$card) {
            $this->redirectWith(url('gift-cards'), 'error', 'Gift card not found.');
        }

        $validated = $this->validate([
            'amount' => 'required|numeric|min:0',
        ]);

        $amount = (float)$validated['amount'];
        $newBalance = (float)$card->current_balance + $amount;

        $db->table('gift_cards')->where('id', $id)->update(['current_balance' => $newBalance]);

        $db->table('gift_card_transactions')->insert([
            'gift_card_id' => $id,
            'type' => 'load',
            'amount' => $amount,
            'created_at' => date(DATE_TIME_FORMAT),
        ]);

        $this->logActivity('reload', 'Reloaded gift card ' . $card->card_number . ' with ' . $amount);

        $this->redirectWith(url('gift-cards'), 'success', 'Gift card reloaded successfully.');
    }

    public function search(): void
    {
        $this->requirePermission('loyalty_giftcards_view');

        $number = $this->request->get('number', '');

        if (empty($number)) {
            $this->json(['success' => false, 'message' => 'Card number is required.']);
            return;
        }

        $card = Database::getInstance()->table('gift_cards')
            ->select('gift_cards.*, c.first_name, c.last_name, c.phone')
            ->leftJoin('customers c', 'gift_cards.customer_id', '=', 'c.id')
            ->where('gift_cards.card_number', $number)
            ->first();

        if (!$card) {
            $this->json(['success' => false, 'message' => 'Gift card not found.']);
            return;
        }

        $this->json(['success' => true, 'data' => $card]);
    }
}
