<?php

namespace App\Modules\Finance\Controllers;

use Core\Controller;
use Core\Auth;

class ExpenseController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireAuth();
    }

    public function index()
    {
        $orgId = Auth::orgId();
        $projectId = (int) $this->getGet('project_id', 0);

        $budgetItems = [];
        if ($projectId) {
            $project = $this->dbQueryOne("SELECT * FROM projects WHERE id = ? AND org_id = ?", [$projectId, $orgId]);
            if (!$project) {
                $this->setFlash('error', 'Project not found.');
                $this->redirect(APP_URL . '/finance/expenses');
            }
            $expenses = $this->dbQuery(
                "SELECT e.*, b.item_name as budget_item_name FROM expenses e LEFT JOIN budget_items b ON e.budget_item_id = b.id WHERE e.project_id = ? ORDER BY e.expense_date DESC",
                [$projectId]
            );
            $budgetItems = $this->dbQuery("SELECT id, item_name FROM budget_items WHERE project_id = ? ORDER BY item_name", [$projectId]);
        } else {
            $expenses = $this->dbQuery(
                "SELECT e.*, p.name as project_name FROM expenses e LEFT JOIN projects p ON e.project_id = p.id WHERE p.org_id = ? ORDER BY e.expense_date DESC LIMIT 100",
                [$orgId]
            );
            $project = null;
        }

        $projects = $this->dbQuery("SELECT id, name FROM projects WHERE org_id = ? ORDER BY name", [$orgId]);

        $this->render('finance/expenses/index', [
            'pageTitle' => 'Expenses',
            'expenses'  => $expenses,
            'project'   => $project,
            'projectId' => $projectId,
            'projects'  => $projects,
            'budgetItems' => $budgetItems,
            'breadcrumb' => [['label' => 'Finance'], ['label' => 'Expenses']],
        ]);
    }

    public function store()
    {
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token.');
            $this->redirect(APP_URL . '/finance/expenses');
        }

        $projectId = (int) $this->getPost('project_id', 0);
        $project = $this->dbQueryOne("SELECT id FROM projects WHERE id = ? AND org_id = ?", [$projectId, Auth::orgId()]);
        if (!$project) {
            $this->setFlash('error', 'Project not found.');
            $this->redirect(APP_URL . '/finance/expenses');
        }

        $amount    = (float) $this->getPost('amount', 0);

        $this->dbExecute(
            "INSERT INTO expenses (project_id, budget_item_id, description, amount, currency, expense_date, vendor_name, reference_number, notes, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())",
            [
                $projectId,
                $this->getPost('budget_item_id') ?: null,
                $this->getPost('description', ''),
                $amount,
                $this->getPost('currency', DEFAULT_CURRENCY),
                $this->getPost('expense_date', date('Y-m-d')),
                $this->getPost('vendor_name', ''),
                $this->getPost('reference_number', ''),
                $this->getPost('notes', ''),
                Auth::id(),
            ]
        );

        $this->setFlash('success', 'Expense recorded successfully.');
        $this->redirect(APP_URL . '/finance/expenses' . ($projectId ? '?project_id=' . $projectId : ''));
    }

    public function delete(int $id)
    {
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token.');
            $this->redirect(APP_URL . '/finance/expenses');
        }

        $expense = $this->dbQueryOne(
            "SELECT e.project_id FROM expenses e INNER JOIN projects p ON e.project_id = p.id WHERE e.id = ? AND p.org_id = ?",
            [$id, Auth::orgId()]
        );
        if (!$expense) {
            $this->setFlash('error', 'Expense not found.');
            $this->redirect(APP_URL . '/finance/expenses');
        }
        $this->dbExecute("DELETE FROM expenses WHERE id = ?", [$id]);
        $this->setFlash('success', 'Expense deleted.');
        $this->redirect(APP_URL . '/finance/expenses?project_id=' . $expense['project_id']);
    }
}
