<?php
// app/Http/Controllers/ExpenseController.php
namespace App\Http\Controllers;

use App\Models\Expense;
use App\Models\ExpenseCategory;
use App\Models\ClientSite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class ExpenseController extends Controller
{
    public function index()
    {
        try {
            $expenses = Auth::user()->expenses()->with(['category', 'clientSite'])->latest()->get();
            return view('expenses.index', compact('expenses'));
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Error loading expenses: ' . $e->getMessage());
        }
    }

    public function create()
    {
        $categories = ExpenseCategory::where('is_active', true)->get();
        $clientSites = ClientSite::where('is_active', true)->get();
        return view('expenses.create', compact('categories', 'clientSites'));
    }

    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'description' => 'required|string|max:255',
                'category_id' => 'required|exists:expense_categories,id',
                'amount' => 'required|numeric|min:0.01|max:100000',
                'expense_date' => 'required|date|before_or_equal:today',
                'business_purpose' => 'string|max:500',
                'client_site_id' => 'required|exists:client_sites,id',
                'receipt' => 'file|mimes:jpeg,png,jpg,pdf|max:2048',
            ]);

            // Handle file upload
            if ($request->hasFile('receipt')) {
                $receiptPath = $request->file('receipt')->store('receipts', 'public');
            }

            // Create expense for the authenticated user
            Auth::user()->expenses()->create([
                'description' => $validated['description'],
                'category_id' => $validated['category_id'],
                'amount' => $validated['amount'],
                'expense_date' => $validated['expense_date'],
                'business_purpose' => $validated['business_purpose'],
                'client_site_id' => $validated['client_site_id'],
                'receipt_path' => $receiptPath ?? null,
                'status' => 'pending',
            ]);

            return redirect()->route('expenses.index')
                ->with('success', 'Expense claim submitted successfully!');

        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Error submitting expense: ' . $e->getMessage());
        }
    }

    public function show(Expense $expense)
    {
        // Authorization - user can only view their own expenses
        if ($expense->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        $expense->load(['category', 'clientSite']);
        return view('expenses.show', compact('expense'));
    }

    public function downloadReceipt(Expense $expense)
    {
        if ($expense->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        if (!$expense->receipt_path || !Storage::disk('public')->exists($expense->receipt_path)) {
            abort(404, 'Receipt file not found.');
        }

        return Storage::disk('public')->download($expense->receipt_path);
    }
}