<?php

namespace App\Http\Controllers;

use App\Models\InstallmentPlan;
use Illuminate\Http\Request;

class PublicController extends Controller
{
    public function showInstallmentPlan($id)
    {
        $plan = InstallmentPlan::findOrFail($id);
        
        // Check if already verified in session
        if (session('verified_plan_' . $id)) {
            return $this->renderPlan($plan);
        }

        return view('public.verify-cnic', compact('plan'));
    }

    public function verifyInstallmentPlan(Request $request, $id)
    {
        $request->validate([
            'cnic_or_phone' => 'required|string',
        ]);

        $plan = InstallmentPlan::with('customer')->findOrFail($id);
        $customer = $plan->customer;

        $input = trim($request->cnic_or_phone);
        
        // Check if input matches CNIC or Phone
        if ($customer->cnic === $input || $customer->phone === $input) {
            session(['verified_plan_' . $id => true]);
            return redirect()->route('public.installment-plan.show', $id);
        }

        return back()->with('error', 'Invalid CNIC or Phone Number. Please try again.');
    }

    private function renderPlan(InstallmentPlan $plan)
    {
        $plan->load(['customer', 'property.block.project', 'installments' => function($q) {
            $q->orderBy('due_date');
        }]);
        
        return view('public.installment-plan', compact('plan'));
    }
}
