<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Expense;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class ExpenseController extends Controller
{
    public function index()
    {
        return view('expenses.index');
    }

    public function getData(Request $request)
    {
        $query = Expense::with('employee');

        if (!Auth::user()->hasRole('Admin')) {
            $query->where('employee_id', Auth::user()->employee_id);
        }

        // Filters
        if ($request->status) {
            $query->where('status', $request->status);
        }
        
        if ($request->is_settled !== null && $request->is_settled !== '') {
            $query->where('is_settled', $request->is_settled);
        }

        $query->when($request->start_date, function ($q) use ($request) {
            return $q->where('date', '>=', $request->start_date);
        })
        ->when($request->end_date, function ($q) use ($request) {
            return $q->where('date', '<=', $request->end_date);
        })
        ->when($request->employee_id, function ($q) use ($request) {
            return $q->where('employee_id', $request->employee_id);
        });

        return DataTables::of($query)
            ->addColumn('employee_name', function ($expense) {
                return $expense->employee->name;
            })
            ->editColumn('status', function ($expense) {
                $class = [
                    'pending' => 'bg-warning',
                    'approved' => 'bg-success',
                    'rejected' => 'bg-danger'
                ][$expense->status];
                return '<span class="badge ' . $class . '">' . ucfirst($expense->status) . '</span>';
            })
            ->editColumn('is_settled', function ($expense) {
                return $expense->is_settled 
                    ? '<span class="badge bg-info">Settled</span>' 
                    : '<span class="badge bg-secondary">Unsettled</span>';
            })
            ->addColumn('action', function ($expense) {
                $html = '<div class="d-flex gap-1 justify-content-center">';
                if ($expense->proof) {
                    $html .= '<a href="' . asset('storage/' . $expense->proof) . '" target="_blank" class="btn-crm-view" title="View Proof"><i class="fas fa-file-invoice"></i></a>';
                }
                
                if (auth()->user()->canAccess('expenses.manage')) {
                    if ($expense->status == 'pending') {
                        $html .= '<button class="btn-crm-approve approve-expense" data-id="' . $expense->id . '" title="Approve"><i class="fas fa-check"></i></button>';
                        $html .= '<button class="btn-crm-reject reject-expense" data-id="' . $expense->id . '" title="Reject"><i class="fas fa-times"></i></button>';
                    } elseif ($expense->status == 'approved' && !$expense->is_settled) {
                        $html .= '<button class="btn-crm-action settle-expense" data-id="' . $expense->id . '" title="Mark Settled"><i class="fas fa-hand-holding-usd"></i></button>';
                    }
                }
                $html .= '</div>';
                return $html;
            })

            ->rawColumns(['status', 'is_settled', 'action'])
            ->make(true);
    }

    public function store(Request $request)
    {
        $request->validate([
            'category' => 'required|string',
            'amount' => 'required|numeric|min:0',
            'date' => 'required|date',
            'proof' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:2048',
        ]);

        $data = $request->only(['category', 'amount', 'date']);
        $data['employee_id'] = Auth::user()->employee_id;
        $data['status'] = 'pending';

        if ($request->hasFile('proof')) {
            $data['proof'] = $request->file('proof')->store('expenses', 'public');
        }

        Expense::create($data);

        return response()->json(['success' => 'Expense submitted successfully.']);
    }

    public function approve($id)
    {
        $expense = Expense::findOrFail($id);
        $expense->update(['status' => 'approved']);
        return response()->json(['success' => 'Expense approved.']);
    }

    public function reject(Request $request, $id)
    {
        $expense = Expense::findOrFail($id);
        $expense->update([
            'status' => 'rejected',
            'rejection_reason' => $request->reason
        ]);
        return response()->json(['success' => 'Expense rejected.']);
    }

    public function settle($id)
    {
        $expense = Expense::findOrFail($id);
        $expense->update(['is_settled' => true]);
        return response()->json(['success' => 'Expense marked as settled.']);
    }

    public function getStats(Request $request)
    {
        $query = Expense::query();
        
        if (!Auth::user()->hasRole('Admin')) {
            $query->where('employee_id', Auth::user()->employee_id);
        }

        // Apply shared filters
        $query->when($request->start_date, function ($q) use ($request) {
            return $q->where('date', '>=', $request->start_date);
        })
        ->when($request->end_date, function ($q) use ($request) {
            return $q->where('date', '<=', $request->end_date);
        })
        ->when($request->employee_id, function ($q) use ($request) {
            return $q->where('employee_id', $request->employee_id);
        });

        $settled = (clone $query)->where('status', 'approved')->where('is_settled', true)->sum('amount');
        $unsettled = (clone $query)->where('status', 'approved')->where('is_settled', false)->sum('amount');
        $pending = (clone $query)->where('status', 'pending')->sum('amount');

        return response()->json([
            'settled' => number_format($settled, 2),
            'unsettled' => number_format($unsettled, 2),
            'pending' => number_format($pending, 2),
            'currency' => \App\Models\BusinessSetting::firstOrNewDefault()->currency_symbol
        ]);
    }
}
