<?php

namespace App\Http\Controllers;

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

class ImportRequestDetailController extends Controller
{
    public function edit($id)
    {
        $importRequest = ImportRequest::findOrFail($id);
        return view('import_requests.details.edit', compact('importRequest'));
    }

    public function update(Request $request, $id)
    {
        $importRequest = ImportRequest::findOrFail($id);

        $request->validate([
            'courier_service' => 'nullable|string|max:255',
            'awb_no' => [
                'nullable',
                'string',
                'max:255',
                'required_with:courier_service'
            ],
            'shipment_reference' => 'nullable|string|max:255',
            'cost' => 'nullable|numeric|min:0',
            'actual_weight' => 'nullable|numeric|min:0',
            'remarks' => 'nullable|string',
            'other_attachment' => 'nullable|file|max:2048',
        ]);
        
        // Manual validation for conditional attachment
        if ($request->filled('courier_service') && !$request->hasFile('other_attachment') && !$importRequest->other_attachment) {
            return back()->withErrors(['other_attachment' => 'The AWB PDF attachment is required when Courier Service is selected.'])->withInput();
        }

        // Notification logic for AWB change
        if ($importRequest->awb_no !== $request->awb_no) {
            // AWB Assigned or Changed
            if (!empty($request->awb_no)) {
                // Assuming 'creator' relationship exists and 'awb_no' is the correct field name
                // Also assuming App\Notifications\AwbAssigned exists and is imported or fully qualified
                $importRequest->creator->notify(new \App\Notifications\AwbAssigned($importRequest, 'Import', $request->awb_no));
            }
        }

        $data = [
            'courier_service' => $request->courier_service,
            'awb_no' => $request->awb_no,
            'shipment_reference' => $request->shipment_reference,
            'cost' => $request->cost,
            'actual_weight' => $request->actual_weight,
            'remarks' => $request->remarks,
            'awb_updated_by' => auth()->id(),
            'awb_updated_at' => now(),
        ];

        if ($request->hasFile('other_attachment')) {
            $data['other_attachment'] = $request->other_attachment->store('import_attachments', 'public');
        }
        
        // Capture original AWB
        $originalAwb = $importRequest->awb_no;

        // Update the request with new data
        $importRequest->update($data);
        
        // If AWB No is updated, send email
        if ($request->filled('awb_no') && $originalAwb !== $request->awb_no) {
             // Determine attachment path
             $attachmentToSend = isset($data['other_attachment']) ? $data['other_attachment'] : $importRequest->other_attachment;

             try {
                $ccEmails = ['CourierBookingForm@jfi.lk'];
                if ($importRequest->shipper && $importRequest->shipper->email) {
                    $ccEmails[] = $importRequest->shipper->email;
                }

                \Illuminate\Support\Facades\Mail::to($importRequest->creator)
                    ->cc($ccEmails)
                    ->send(new \App\Mail\ImportRequestAwbUpdatedMail($importRequest, $attachmentToSend));

             } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Failed to send import AWB update email: ' . $e->getMessage());
                // Use session flash since we redirect after this block
                session()->flash('warning', 'AWB updated, but failed to send email: ' . $e->getMessage());
             }
        }

        return redirect()->route('import_requests.index')
            ->with('success', 'Import Request details updated successfully!');
    }
}
