<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Expense;
use App\Models\ExpenseCategory;

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

        $expenseModel = new Expense();
        $categoryModel = new ExpenseCategory();

        $params = [
            'search' => $_GET['search'] ?? '',
            'category_id' => $_GET['category_id'] ?? ''
        ];

        $expenses = $expenseModel->search($params);
        $categories = $categoryModel->all();

        $title = 'Expenses';
        require_once __DIR__ . '/../../views/admin/expenses.php';
    }

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

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $expenseModel = new Expense();
            
            $data = [
                'id' => $_POST['id'] ?? null,
                'expense_category_id' => $_POST['expense_category_id'],
                'title' => $_POST['title'],
                'amount' => $_POST['amount'],
                'date' => $_POST['date'],
                'description' => $_POST['description'] ?? '',
                'payment_method' => $_POST['payment_method'] ?? 'Cash',
                'attachment' => $_POST['old_attachment'] ?? null
            ];

            // Handle file upload
            if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '/uploads/expenses/';
                if (!is_dir(__DIR__ . '/../../public' . $uploadDir)) {
                    mkdir(__DIR__ . '/../../public' . $uploadDir, 0777, true);
                }

                $fileName = time() . '_' . basename($_FILES['attachment']['name']);
                $targetFile = __DIR__ . '/../../public' . $uploadDir . $fileName;

                if (move_uploaded_file($_FILES['attachment']['tmp_name'], $targetFile)) {
                    // Delete old attachment if exists
                    if (!empty($data['attachment'])) {
                        $oldFile = __DIR__ . '/../../public' . $data['attachment'];
                        if (file_exists($oldFile)) unlink($oldFile);
                    }
                    $data['attachment'] = $uploadDir . $fileName;
                }
            }

            try {
                $expenseModel->save($data);
                $_SESSION['toast'] = ['message' => $data['id'] ? 'Expense updated!' : 'Expense recorded!', 'type' => 'success'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/expenses');
        exit;
    }

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

        if (isset($_GET['id'])) {
            try {
                $expenseModel = new Expense();
                $expenseModel->delete($_GET['id']);
                $_SESSION['toast'] = ['message' => 'Expense record deleted.', 'type' => 'info'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error deleting expense: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/expenses');
        exit;
    }
}
