<?php

namespace App\Http\Controllers\Payments;

use App\Http\Controllers\Controller;
use App\Models\Job;
use App\Models\Deposit;
use App\Services\StripeService;
use Illuminate\Http\Request;

class PayLinkController extends Controller
{
    public function show(Request $request, Job $job)
    {
        // Your job has charge in cents (stored) but shown as dollars in UI.
        $chargeCents = (int) $job->charge_amount_cents;    // 0 for transfers
        $holdCents   = (int) $job->hold_cents;             // e.g., 50000 for $500

        // Compute page "mode"
        $mode = ($chargeCents > 0 && $holdCents > 0) ? 'charge+hold'
              : ($chargeCents > 0 ? 'charge'
              : ($holdCents > 0   ? 'hold' : 'none'));

        // Short-circuit only if there truly is nothing to do
        if ($mode === 'none') {
            return inertia('Pay/PayPage', [
                'mode' => 'none',
                'job'  => $job->only(['id','ref','start_at','end_at']),
                'amount_due_cents' => 0,
                'hold_cents'       => 0,
                'client_secret'    => null,
                'brand'            => $request->get('brand', 'dreamdrives'),
            ]);
        }

        // Ensure a Deposit exists for the hold path
        $deposit = null;
        if ($holdCents > 0) {
            $deposit = Deposit::firstOrCreate(
                ['job_id' => $job->id, 'type' => 'booking_deposit', 'status' => 'pending'],
                ['amount_cents' => $holdCents]
            );
        }

        // If this is hold-only, create a manual-capture PaymentIntent up front
        $clientSecret = null;
        if ($mode === 'hold') {
            $stripe = StripeService::make();
            $pi = $stripe->createManualCapturePI([
                'amount_cents' => $holdCents,
                'currency'     => 'nzd',
                'setup_future_usage' => 'off_session',
                'metadata' => [
                    'kind'       => 'deposit_auth',
                    'deposit_id' => $deposit?->id,
                    'job_id'     => $job->id,
                    'job_ref'    => $job->ref ?? $job->id,
                ],
            ]);
            $deposit->update(['stripe_payment_intent_id' => $pi->id]);
            $clientSecret = $pi->client_secret;
        }

        // Render page (Inertia/React). For charge or charge+hold you may create PI later on POST.
        return inertia('Pay/PayPage', [
            'mode' => $mode,
            'job'  => $job->only(['id','ref','start_at','end_at']),
            'amount_due_cents' => $chargeCents,
            'hold_cents'       => $holdCents,
            'client_secret'    => $clientSecret, // present for hold-only
            'brand'            => $request->get('brand', 'dreamdrives'),
        ]);
    }
}
