<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\FeeHead;
use App\Models\Setting;

class FeeHeadController {
    public function index() {
        if (!Auth::hasPermission('fees_head')) {
            redirect('/login');
            exit;
        }

        $feeHeadModel = new FeeHead();
        $params = [
            'search' => $_GET['search'] ?? '',
            'is_active' => $_GET['is_active'] ?? '',
            'is_mandatory' => $_GET['is_mandatory'] ?? '',
        ];

        $feeHeads = $feeHeadModel->getAll($params);
        
        $settingModel = new Setting();
        $siteSettings = $settingModel->getAll();
        
        $title = 'Fee Heads Master';
        require_once __DIR__ . '/../../views/admin/fee_heads.php';
    }

    public function save() {
        if (!Auth::hasPermission('fees_head')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $feeHeadModel = new FeeHead();
            $data = [
                'name' => $_POST['name'],
                'description' => $_POST['description'] ?? '',
                'default_amount' => $_POST['default_amount'] ?: null,
                'frequency' => $_POST['frequency'] ?? 'One-time',
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
                'is_mandatory' => isset($_POST['is_mandatory']) ? 1 : 0,
            ];

            if (!empty($_POST['id'])) {
                $data['id'] = $_POST['id'];
            }

            try {
                $feeHeadModel->save($data);
                $_SESSION['toast'] = ['message' => 'Fee head saved successfully!', 'type' => 'success'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/fee-heads');
    }

    public function delete() {
        if (!Auth::hasPermission('fees_head')) {
            redirect('/login');
            exit;
        }

        $id = $_GET['id'] ?? null;
        if ($id) {
            $feeHeadModel = new FeeHead();
            try {
                $feeHeadModel->delete($id);
                $_SESSION['toast'] = ['message' => 'Fee head deleted!', 'type' => 'success'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/fee-heads');
    }

    public function toggleStatus() {
        if (!Auth::hasPermission('fees_head')) {
            redirect('/login');
            exit;
        }

        $id = $_GET['id'] ?? null;
        if ($id) {
            $feeHeadModel = new FeeHead();
            $feeHeadModel->toggleStatus($id);
        }
        redirect('/admin/fee-heads');
    }
}
