<?php

declare(strict_types=1);

namespace App\Modules\Invitation;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Session;

/**
 * GiftController — HTTP Handler for Couple Portal Wedding Gift management.
 *
 * @package Inveetaire
 */
class GiftController extends BaseController
{
    protected string $layout = 'couple';
    private GiftModel $model;
    private InvitationService $invitationService;

    public function __construct()
    {
        parent::__construct();
        $this->model = new GiftModel();
        $this->invitationService = new InvitationService();
    }

    /**
     * Display the gift management page.
     */
    public function index(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        
        try {
            // We need the invitation ID for this workspace
            $invitation = $this->invitationService->getInvitationDetails($workspaceId);
            $invitationId = (int) $invitation['id'];
            
            $settings = $this->model->getSettingsByInvitationId($invitationId);
            $accounts = [];
            
            if ($settings) {
                $accounts = $this->model->getAccountsBySettingId((int) $settings['id']);
            } else {
                // Defaults if never saved before
                $settings = [
                    'id' => 0,
                    'is_enabled' => 1,
                    'title' => 'Wedding Gift & Angpau',
                    'subtitle' => 'For friends and family who wish to send wedding tokens or digital gifts, details are provided below:'
                ];
            }
            
            $this->render('invitation/gift', [
                'pageTitle' => 'Wedding Gift',
                'settings' => $settings,
                'accounts' => $accounts
            ]);
        } catch (\Throwable $e) {
            Session::setFlash('error', 'Unable to load gift settings: ' . $e->getMessage());
            $this->redirect('/app/couple/dashboard');
        }
    }

    /**
     * Save gift section settings.
     */
    public function updateSettings(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        
        try {
            $invitation = $this->invitationService->getInvitationDetails($workspaceId);
            $invitationId = (int) $invitation['id'];
            
            $data = $request->post();
            $isEnabled = !empty($data['is_enabled']);
            $title = trim($data['title'] ?? 'Wedding Gift & Angpau');
            $subtitle = trim($data['subtitle'] ?? '');
            
            $this->model->saveSettings($invitationId, $isEnabled, $title, $subtitle);
            
            Session::setFlash('success', 'Wedding gift settings saved successfully.');
        } catch (\Throwable $e) {
            Session::setFlash('error', 'Error saving settings: ' . $e->getMessage());
        }
        
        $this->redirect('/app/couple/invitation/gift');
    }

    /**
     * Save a gift account.
     */
    public function saveAccount(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        
        try {
            $invitation = $this->invitationService->getInvitationDetails($workspaceId);
            $settings = $this->model->getSettingsByInvitationId((int) $invitation['id']);
            
            if (!$settings) {
                // Auto create settings if they don't exist yet
                $this->model->saveSettings((int) $invitation['id'], true, 'Wedding Gift & Angpau', '');
                $settings = $this->model->getSettingsByInvitationId((int) $invitation['id']);
            }
            
            $settingId = (int) $settings['id'];
            
            $data = $request->post();
            $accountId = (int) ($data['account_id'] ?? 0);
            $providerName = trim($data['provider_name'] ?? '');
            $accountNumber = trim($data['account_number'] ?? '');
            $accountHolder = trim($data['account_holder'] ?? '');
            $isActive = !isset($data['is_active']) || !empty($data['is_active']); // default true
            $sortOrder = (int) ($data['sort_order'] ?? 0);
            
            if (empty($providerName) || empty($accountNumber) || empty($accountHolder)) {
                throw new \Exception('Provider Name, Account Number, and Account Holder are required.');
            }
            
            $this->model->saveAccount($settingId, $accountId, $providerName, $accountNumber, $accountHolder, $isActive, $sortOrder);
            
            Session::setFlash('success', 'Gift account saved successfully.');
        } catch (\Throwable $e) {
            Session::setFlash('error', $e->getMessage());
        }
        
        $this->redirect('/app/couple/invitation/gift');
    }

    /**
     * Delete a gift account.
     */
    public function deleteAccount(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        
        try {
            $invitation = $this->invitationService->getInvitationDetails($workspaceId);
            $settings = $this->model->getSettingsByInvitationId((int) $invitation['id']);
            
            $data = $request->post();
            $accountId = (int) ($data['account_id'] ?? 0);
            
            if ($settings && $accountId > 0) {
                $this->model->deleteAccount((int) $settings['id'], $accountId);
                Session::setFlash('success', 'Gift account deleted successfully.');
            }
        } catch (\Throwable $e) {
            Session::setFlash('error', 'Error deleting account: ' . $e->getMessage());
        }
        
        $this->redirect('/app/couple/invitation/gift');
    }
}
