<?php
class TaxController {
    public function index(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('tax.manage');
        
        $taxGroups = TaxGroup::getActive();
        
        $pageTitle = 'Tax Groups';
        ob_start();
        include APP_ROOT . '/views/tenant/tax/index.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }
    
    public function create(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('tax.manage');
        
        $pageTitle = 'Create Tax Group';
        ob_start();
        include APP_ROOT . '/views/tenant/tax/create.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }
    
    public function store(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('tax.manage');
        Security::checkCsrf();
        
        try {
            $tid = Auth::tenantId();
            
            $data = [
                'name' => Security::sanitize($_POST['name']),
                'rate' => (float)$_POST['rate'],
                'type' => Security::sanitize($_POST['type']),
                'description' => Security::sanitize($_POST['description'] ?? ''),
                'is_active' => 1
            ];
            
            $taxGroupId = TaxGroup::create($data);
            
            flash('success', 'Tax group created successfully');
            redirect('tax');
        } catch (Exception $e) {
            flash('error', $e->getMessage());
            redirectBack();
        }
    }
    
    public function edit(string $id): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('tax.manage');
        
        $taxGroup = TaxGroup::find((int)$id);
        if (!$taxGroup) { flash('error', 'Tax group not found'); redirect('tax'); }
        
        $pageTitle = 'Edit Tax Group';
        ob_start();
        include APP_ROOT . '/views/tenant/tax/edit.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }
    
    public function update(string $id): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('tax.manage');
        Security::checkCsrf();
        
        try {
            $data = [
                'name' => Security::sanitize($_POST['name']),
                'rate' => (float)$_POST['rate'],
                'type' => Security::sanitize($_POST['type']),
                'description' => Security::sanitize($_POST['description'] ?? ''),
                'is_active' => isset($_POST['is_active']) ? 1 : 0
            ];
            
            TaxGroup::update((int)$id, $data);
            
            flash('success', 'Tax group updated successfully');
            redirect('tax');
        } catch (Exception $e) {
            flash('error', $e->getMessage());
            redirectBack();
        }
    }
    
    public function destroy(string $id): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requireRole(['admin','owner']);
        Security::checkCsrf();
        
        try {
            // Check if tax group is being used
            $tid = Auth::tenantId();
            $stmt = db()->prepare("SELECT COUNT(*) FROM products WHERE tax_group_id = ? AND tenant_id = ?");
            $stmt->execute([$id, $tid]);
            $count = $stmt->fetchColumn();
            
            if ($count > 0) {
                flash('error', 'Cannot delete tax group that is in use by products');
                redirectBack();
            }
            
            TaxGroup::delete((int)$id);
            flash('success', 'Tax group deleted successfully');
            redirect('tax');
        } catch (Exception $e) {
            flash('error', $e->getMessage());
            redirectBack();
        }
    }
}
