<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\ChequeApplication;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ChequeController extends Controller
{
    // Show the cheque redemption form
    public function create()
    {
        return view('user.cheque.create');
    }

    // Store new cheque application
    public function store(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'bank_name' => 'required|string|max:255',
            'cheque_number' => 'required|string|max:50',
            'cheque_date' => 'required|date',
            'drawer_name' => 'required|string|max:255',
            'additional_details' => 'nullable|string|max:1000',
            'cheque_image' => 'required|image|mimes:jpeg,png,jpg|max:5120' // 5MB max
        ]);

        try {
            // Handle file upload
            $imagePath = $request->file('cheque_image')->store('cheque_images', 'public');

            // Create the application
            ChequeApplication::create([
                'user_id' => Auth::id(),
                'amount' => $request->amount,
                'bank_name' => $request->bank_name,
                'cheque_number' => $request->cheque_number,
                'cheque_date' => $request->cheque_date,
                'drawer_name' => $request->drawer_name,
                'additional_details' => $request->additional_details,
                'cheque_image_path' => $imagePath,
                'status' => 'pending'
            ]);

            return redirect()->route('user.cheque.my-applications')
                ->with('success', 'Cheque application submitted successfully! Please wait for admin approval.');

        } catch (\Exception $e) {
            return back()->with('error', 'Error submitting application. Please try again.');
        }
    }

    // Show user's own applications
    public function myApplications()
    {
        $applications = ChequeApplication::where('user_id', Auth::id())
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('user.cheque.my-applications', compact('applications'));
    }
}