<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Services\StripeService;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    protected $stripe;

    public function __construct(StripeService $stripe)
    {
        $this->stripe = $stripe;
    }

    public function createPaymentIntent(Request $request, Booking $booking)
    {
        // Calculate amount based on hours * rate
        // For simplicity, let's assume 1 hour for now or calculate from actual times
        $durationHours = $booking->actual_start_time->diffInHours($booking->actual_end_time);
        $amount = $durationHours * $booking->job->rate_per_hour;
        
        // Stripe expects amount in cents
        $amountCents = (int) ($amount * 100);

        try {
            $intent = $this->stripe->createPaymentIntent($amountCents, 'gbp', [
                'booking_id' => $booking->id,
            ]);

            return response()->json([
                'clientSecret' => $intent->client_secret,
                'isMock' => $this->stripe->isMockMode(),
                'mockIntent' => $this->stripe->isMockMode() ? $intent : null,
            ]);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function confirmPayment(Request $request, Booking $booking)
    {
        // In a real flow, this would be a webhook.
        // For mock/simple flow, we trust the client calls this after successful "mock" payment.
        
        $booking->update(['status' => 'paid']);
        return response()->json(['message' => 'Payment confirmed']);
    }
}
