<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\ChangeRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ChangeRequestController extends Controller
{
    public function index(Request $request): Response
    {
        $employee = $request->user()->employee;

        return Inertia::render('portal/requests', [
            'requests' => ChangeRequest::where('employee_id', $employee->id)
                ->latest()
                ->get()
                ->map(fn (ChangeRequest $r) => [
                    'id' => $r->id,
                    'target' => $r->target,
                    'proposed_values' => $r->proposed_values,
                    'status' => $r->status,
                    'review_note' => $r->review_note,
                    'created_at' => $r->created_at?->toDateTimeString(),
                    'reviewed_at' => $r->reviewed_at?->toDateTimeString(),
                ]),
            'current' => [
                'bank' => optional($employee->bankAccount)->only(['bank_name', 'branch_bank', 'account_type', 'account_number']),
                'pension' => optional($employee->pensionAccount)->only(['pension_house', 'pen_number']),
                'contact' => ['phone' => $employee->phone],
            ],
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $employee = $request->user()->employee;

        $target = $request->input('target');
        $rules = match ($target) {
            ChangeRequest::TARGET_BANK => [
                'target' => 'required',
                'values.bank_name' => 'required|string|max:255',
                'values.account_number' => 'required|string|max:32',
                'values.account_type' => 'nullable|string|max:64',
                'values.branch_bank' => 'nullable|string|max:255',
            ],
            ChangeRequest::TARGET_PENSION => [
                'target' => 'required',
                'values.pension_house' => 'required|string|max:255',
                'values.pen_number' => 'required|string|max:32',
            ],
            ChangeRequest::TARGET_CONTACT => [
                'target' => 'required',
                'values.phone' => 'required|string|max:32',
            ],
            default => ['target' => 'required|in:BANK,PENSION,CONTACT'],
        };
        $validated = $request->validate($rules);

        ChangeRequest::create([
            'employee_id' => $employee->id,
            'requested_by' => $request->user()->id,
            'target' => $target,
            'proposed_values' => $validated['values'] ?? [],
            'status' => ChangeRequest::STATUS_PENDING,
        ]);

        return back()->with('success', 'Change request submitted for review.');
    }
}
