<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\Customer;
use App\Models\Property;
use Illuminate\Http\Request;

class BookingController extends Controller
{
    public function index()
    {
        $bookings = Booking::with(['customer', 'property.block.project'])->latest()->paginate(15);
        return view('bookings.index', compact('bookings'));
    }

    public function create()
    {
        $customers = Customer::all();
        $properties = Property::where('status', 'Available for Sale')->with('block.project')->get();
        return view('bookings.create', compact('customers', 'properties'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'property_id' => 'required|exists:properties,id',
            'total_price' => 'required|numeric',
            'discount' => 'nullable|numeric',
            'booking_amount' => 'required|numeric',
            'booking_date' => 'required|date',
            'payment_method' => 'required|string',
            'payment_proof' => 'nullable|file|max:10240',
        ]);

        // Availability Check
        $property = \App\Models\Property::findOrFail($validated['property_id']);
        if (!in_array($property->status, ['Available', 'Reserved'])) {
            return back()->withInput()->with('error', 'This plot has already been sold or is unavailable for booking.');
        }

        // Document Verification Check (Rule 11)
        $blockOnRejected = \App\Models\Setting::where('key', 'block_booking_on_rejected_docs')->value('value') == 1;
        if ($blockOnRejected) {
            $hasRejectedDocs = \App\Models\CustomerDocument::where('customer_id', $validated['customer_id'])
                ->where('status', 'Rejected')
                ->exists();
            if ($hasRejectedDocs) {
                return back()->withInput()->with('error', 'Cannot proceed with booking: This customer has rejected documents that must be resolved first.');
            }
        }

        $booking = Booking::create([
            'customer_id' => $validated['customer_id'],
            'property_id' => $validated['property_id'],
            'total_price' => $validated['total_price'],
            'discount' => $validated['discount'],
            'booking_amount' => $validated['booking_amount'],
            'booking_date' => $validated['booking_date'],
        ]);
        
        // Update property status
        $booking->property->update(['status' => 'Reserved']);

        $proofPath = null;
        if ($request->hasFile('payment_proof')) {
            $proofPath = $request->file('payment_proof')->store('payment_proofs', 'public');
        }

        // Create an Invoice for the down payment
        $invoice = \App\Models\Invoice::create([
            'customer_id' => $validated['customer_id'],
            'property_id' => $validated['property_id'],
            'invoice_number' => 'INV-' . strtoupper(uniqid()),
            'type' => 'Down Payment',
            'amount' => $validated['booking_amount'],
            'date' => $validated['booking_date'],
            'status' => 'Pending Verification',
            'payment_method' => $validated['payment_method'],
            'payment_proof' => $proofPath,
        ]);

        // Log the transaction
        $transaction = \App\Models\Transaction::create([
            'customer_id' => $validated['customer_id'],
            'invoice_id' => $invoice->id,
            'amount' => $validated['booking_amount'],
            'payment_method' => $validated['payment_method'],
            'proof_path' => $proofPath,
            'status' => 'Pending',
        ]);

        // Send WhatsApp Notification (Rule 18)
        $whatsAppService = app(\App\Services\WhatsAppService::class);
        $templateId = \App\Models\Setting::where('key', 'wa_template_booking_approved')->value('value');
        if ($templateId && $booking->customer->phone) {
            $bodyVariables = [
                $booking->customer->full_name ?? 'Customer',
                $booking->property->plot_number ?? 'Plot'
            ];
            $whatsAppService->sendTemplateMessage($booking->customer->phone, $templateId, $bodyVariables);
        }

        return redirect()->route('bookings.index')->with('success', 'Booking created and payment logged successfully.');
    }

    public function show(Booking $booking)
    {
        $booking->load(['customer', 'property.block.project']);
        return view('bookings.show', compact('booking'));
    }

    public function cancel(Booking $booking, \App\Services\CancellationService $cancellationService)
    {
        $refundData = $cancellationService->cancelBooking($booking);
        
        return back()->with('success', 'Booking cancelled successfully. Paid: ' . number_format($refundData['paid']) . ', Deduction: ' . number_format($refundData['deduction']) . ', Refund: ' . number_format($refundData['refund']));
    }

    public function reject(Booking $booking)
    {
        $booking->update(['status' => 'Rejected']);
        $booking->property->update(['status' => 'Available for Sale']);
        return back()->with('success', 'Booking rejected successfully.');
    }

    public function destroy(Booking $booking)
    {
        $booking->property->update(['status' => 'Available for Sale']);
        $booking->delete();
        return redirect()->route('bookings.index')->with('success', 'Booking deleted successfully.');
    }

    public function uploadDocument(Request $request, Booking $booking)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'document' => 'required|file|max:10240', // 10MB
        ]);

        if ($request->hasFile('document')) {
            $path = $request->file('document')->store('booking_documents', 'public');
            
            $booking->documents()->create([
                'title' => $request->title,
                'file_path' => $path,
            ]);

            return back()->with('success', 'Document uploaded successfully.');
        }

        return back()->with('error', 'No file was uploaded.');
    }

    public function deleteDocument(\App\Models\BookingDocument $document)
    {
        \Illuminate\Support\Facades\Storage::disk('public')->delete($document->file_path);
        $document->delete();
        
        return back()->with('success', 'Document deleted successfully.');
    }

    public function verifyDocument(\App\Models\BookingDocument $document)
    {
        $document->update(['status' => 'Verified']);
        return back()->with('success', 'Document verified successfully.');
    }

    public function rejectDocument(\App\Models\BookingDocument $document)
    {
        $document->update(['status' => 'Rejected']);
        return back()->with('success', 'Document rejected.');
    }
}
