<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Courier;
use App\Models\Settings;
use App\Models\CourierUpdate;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use App\Mail\CourierCreated;
use Illuminate\Support\Facades\Mail;

class CourierController extends Controller
{
    // Show all couriers
    public function index()
    {
        $couriers = Courier::latest()->paginate(15);
    $title  = 'Manage Couriers';
        return view('admin.couriers.index', compact('couriers','title'));
    }

    // Show create form
    public function create()
    {
        
          $settings = Settings::where('id', '=', '1')->first();

        // Generate a unique tracking code (you can customize this)
     // Get the first two uppercase letters of the site name
$prefix = strtoupper(substr($settings->site_name, 0, 2));

// Generate the rest of the tracking code
$randomCode = strtoupper(Str::random(8));

// Combine them
$tracking_code = $prefix . $randomCode;
$title = "create courier";
        return view('admin.couriers.create',compact('tracking_code','title'));
        
    }

    // Store new courier
    public function store(Request $request)
    {
        $request->validate([
            'sender_name' => 'required|string|max:255',
            'sender_email' => 'required|email|max:255',
            'sender_address' => 'required|string',
            'receiver_name' => 'required|string|max:255',
            'receiver_email' => 'required|email|max:255',
            'receiver_contact' => 'required|string|max:50',
            'receiver_address' => 'required|string',
            'tracking_code' => 'required|string|max:255',
            'description' => 'nullable|string',
            'quantity' => 'required|integer|min:1',
            'weight' => 'nullable|numeric|min:0',
            'status' => 'required|string|max:100',
            'shipment_progress' => 'nullable|string|max:50',
            'origin' => 'required|string|max:255',
            'current_location' => 'nullable|string|max:255',
            'destination' => 'required|string|max:255',
            'freight_cost' => 'nullable|numeric|min:0',
            'payment_mode' => 'required|string|max:255',
            'shipping_mode' => 'required|string|max:255',
            'estimated_delivery' => 'nullable|date',
            'dispatch_date' => 'nullable|date',
            'delivery_completion' => 'nullable|boolean',
            'photo' => 'nullable|image|max:2048', // max 2MB
        ]);
        $settings = Settings::where('id', '=', '1')->first();

        // Generate a unique tracking code (you can customize this)
     // Get the first two uppercase letters of the site name
$prefix = strtoupper(substr($settings->site_name, 0, 2));

// Generate the rest of the tracking code
$randomCode = strtoupper(Str::random(8));

// Combine them
$tracking_code = $prefix . $randomCode;

        // Handle photo upload
        $photoPath = null;
        if ($request->hasFile('photo')) {
            $photoPath = $request->file('photo')->store('courier_photos', 'public');
        }

        $courier =Courier::create([
            'tracking_code' =>  $request->tracking_code,
            'sender_name' => $request->sender_name,
            'sender_email' => $request->sender_email,
            'sender_address' => $request->sender_address,
            'receiver_name' => $request->receiver_name,
            'receiver_email' => $request->receiver_email,
            'receiver_contact' => $request->receiver_contact,
            'receiver_address' => $request->receiver_address,
            'description' => $request->description,
            'quantity' => $request->quantity,
            'weight' => $request->weight,
            'status' => $request->status,
            'payment_mode' => $request->payment_mode,
            'shipping_mode' => $request->shipping_mode,
            'shipment_progress' => $request->shipment_progress,
            'origin' => $request->origin,
            'current_location' => $request->current_location,
            'destination' => $request->destination,
            'freight_cost' => $request->freight_cost,
            'estimated_delivery' => $request->estimated_delivery,
            'dispatch_date' => $request->dispatch_date,
            'delivery_completion' => $request->delivery_completion ?? false,
            'photo' => $photoPath,
        ]);
    Mail::to([$courier->sender_email, $courier->receiver_email])
    ->send(new CourierCreated($courier));
        return redirect()->route('couriers.index')->with('success', 'Courier created successfully.');
    }

    // Show details of a courier including updates
    public function show(Courier $courier)
    {
        $courier->load('updates');
        return view('admin.couriers.show', compact('courier'));
    }

    // Show edit form
    public function edit(Courier $courier)
    {
        return view('admin.couriers.edit', compact('courier'));
    }

    // Update courier info
    public function update(Request $request, Courier $courier)
    {
        $request->validate([
            'sender_name' => 'required|string|max:255',
            'sender_email' => 'required|email|max:255',
            'sender_address' => 'required|string',
            'receiver_name' => 'required|string|max:255',
            'receiver_email' => 'required|email|max:255',
            'receiver_contact' => 'required|string|max:50',
            'receiver_address' => 'required|string',
            'description' => 'nullable|string',
             'tracking_code' => 'required|string|max:255',
            'quantity' => 'required|integer|min:1',
            'weight' => 'nullable|numeric|min:0',
            'status' => 'required|string|max:100',
             'payment_mode' => 'required|string|max:255',
            'shipping_mode' => 'required|string|max:255',
            'shipment_progress' => 'nullable|string|max:50',
            'origin' => 'required|string|max:255',
            'current_location' => 'nullable|string|max:255',
            'destination' => 'required|string|max:255',
            'freight_cost' => 'nullable|numeric|min:0',
            'estimated_delivery' => 'nullable|date',
            'dispatch_date' => 'nullable|date',
            'delivery_completion' => 'nullable|boolean',
            'photo' => 'nullable|image|max:2048',
        ]);

        // Handle photo upload and delete old photo if exists
        if ($request->hasFile('photo')) {
            if ($courier->photo) {
                Storage::disk('public')->delete($courier->photo);
            }
            $courier->photo = $request->file('photo')->store('courier_photos', 'public');
        }



        $courier->update([
            'sender_name' => $request->sender_name,
            'sender_email' => $request->sender_email,
            'sender_address' => $request->sender_address,
            'receiver_name' => $request->receiver_name,
            'receiver_email' => $request->receiver_email,
            'receiver_contact' => $request->receiver_contact,
            'receiver_address' => $request->receiver_address,
            'description' => $request->description,
            'quantity' => $request->quantity,
             'tracking_code' => $request->tracking_code,
            'weight' => $request->weight,
            'status' => $request->status,
            'shipment_progress' => $request->shipment_progress,
            'payment_mode' => $request->payment_mode,
            'shipping_mode' => $request->shipping_mode,
            'origin' => $request->origin,
            'current_location' => $request->current_location,
            'destination' => $request->destination,
            'freight_cost' => $request->freight_cost,
            'estimated_delivery' => $request->estimated_delivery,
            'dispatch_date' => $request->dispatch_date,
            'delivery_completion' => $request->delivery_completion ?? false,
            'photo' => $courier->photo,
        ]);

        return redirect()->route('couriers.show', $courier)->with('success', 'Courier updated successfully.');
    }

    // Delete courier and related updates (cascade)
    public function destroy(Courier $courier)
    {
        if ($courier->photo) {
            Storage::disk('public')->delete($courier->photo);
        }
        $courier->delete();

        return redirect()->route('couriers.index')->with('success', 'Courier deleted successfully.');
    }
}
