<?php

namespace App\Http\Controllers;

use App\Models\Pricing;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class PricingController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [

            new Middleware(
                'permission:settings.view',
                only: ['index']
            ),

            new Middleware(
                'permission:settings.edit',
                only: ['store', 'update']
            ),
        ];
    }

    public function index()
    {
        $pricings = Pricing::latest()->get();

        return view(
            'pricings.index',
            compact('pricings')
        );
    }

    public function store(Request $request)
    {
        $request->validate([
            'cargo_type' => 'required',
            'device_type' => 'required',
            'amount' => 'required|numeric|min:0'
        ]);

        $exists = Pricing::where(
            'cargo_type',
            $request->cargo_type
        )
            ->where(
                'device_type',
                $request->device_type
            )
            ->exists();

        if ($exists) {

            return back()->with(
                'error',
                $request->device_type .
                    ' pricing already exists. Please edit it instead.'
            );
        }

        Pricing::create([

            'cargo_type' => $request->cargo_type,

            'device_type' => $request->device_type,

            'amount' => $request->amount,

            'status' => 1,

            'created_by' => Auth::id(),

            'updated_by' => Auth::id(),

        ]);
        return back()->with(
            'success',
            'Pricing created successfully.'
        );
    }

    public function update(
        Request $request,
        Pricing $pricing
    ) {
        $request->validate([
            'amount' => 'required|numeric|min:0',
            'status' => 'required'
        ]);

        $pricing->update([

            'amount' => $request->amount,

            'status' => $request->status,

            'updated_by' => Auth::id(),
        ]);

        return back()->with(
            'success',
            'Pricing updated successfully.'
        );
    }



//my code
// public function SaveActivationWithT1(Request $request)
// {
//     // return response()->json(['Error' => 'Activation UnderMaintence Contact CMC']);

//     $deviceNumber = trim((string) $request->deviceNumber);

//     if ($deviceNumber === '') {
//         return response()->json([
//             'Error' => 'e-Seal Not Found, Please Check E-Seal Status you want to activate'
//         ]);
//     }

//     $activationType = (int) $request->activation_type;

//     if (!in_array($activationType, [1, 2], true)) {
//         return response()->json([
//             'Error' => 'Invalid activation type'
//         ]);
//     }

//     DB::beginTransaction();

//     try {

//         $user = Auth::user();

//         /*
//         |--------------------------------------------------------------------------
//         | Validate duplicate T1
//         |--------------------------------------------------------------------------
//         */

//         if ($activationType === 1 && is_array($request->t1Number)) {

//             foreach ($request->t1Number as $t1Number) {

//                 $exists = T1Detail::where('t1_number', $t1Number)
//                     ->whereHas('activation', function ($query) use ($request) {
//                         $query->where('departure_office', $request->dipartureOffice)
//                             ->where('entryyear', $request->entryyear);
//                     })
//                     ->exists();

//                 if ($exists) {

//                     DB::rollBack();

//                     return response()->json([
//                         'Error' => 'T1 number is already activated: ' . $t1Number
//                     ]);
//                 }
//             }
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Validate Exit Note
//         |--------------------------------------------------------------------------
//         */

//         if ($activationType === 2 && $request->exitNoteNo) {

//             $exists = T1Detail::where('exit_note_no', $request->exitNoteNo)
//                 ->whereHas('activation', function ($query) use ($request) {
//                     $query->where('departure_office', $request->dipartureOffice);
//                 })
//                 ->exists();

//             if ($exists) {

//                 DB::rollBack();

//                 return response()->json([
//                     'Error' => 'Exit Note Number is already activated: ' . $request->exitNoteNo
//                 ]);
//             }
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Lock Device Row (Prevents Duplicate Activation)
//         |--------------------------------------------------------------------------
//         */

//         $device = DB::table('devices')
//             ->select(
//                 'current_messages.*',
//                 'devices.*',
//                 'received_devices.status as received_status'
//             )
//             ->leftJoin(
//                 'received_devices',
//                 'devices.id',
//                 '=',
//                 'received_devices.device_id'
//             )
//             ->leftJoin(
//                 'current_messages',
//                 'devices.id',
//                 '=',
//                 'current_messages.device_id'
//             )
//             ->where(function ($query) use ($deviceNumber) {

//                 $query->where(
//                     'devices.serial_number',
//                     'LIKE',
//                     '%' . $deviceNumber
//                 )
//                 ->orWhere(
//                     'devices.serial_number',
//                     'LIKE',
//                     '%' . substr($deviceNumber, -4)
//                 );

//             })
//             ->lockForUpdate()
//             ->first();

//         if (!$device) {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Device not found for the provided serial number'
//             ]);
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Destination Validation
//         |--------------------------------------------------------------------------
//         */

//         if (
//             $request->destination === '11PBW'
//             && is_null($request->pbw_id)
//         ) {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'The Private bonded office field is required.'
//             ]);
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Seal Reporting Validation
//         |--------------------------------------------------------------------------
//         */

//         if (!$this->checkSealReporting($device->datetime)) {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Seal Not Reporting within 10 minutes ago, Check Reporting Time'
//             ]);
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Validate TIN
//         |--------------------------------------------------------------------------
//         */

//         if ($activationType === 2) {

//             $tinLengthCA = strlen((string) $request->clearingAgentTin);

//             if (
//                 !is_numeric($request->clearingAgentTin)
//                 || $tinLengthCA !== 9
//             ) {

//                 DB::rollBack();

//                 return response()->json([
//                     'Error' => 'Clearing agent TIN number should be exactly 9 digits'
//                 ]);
//             }

//             if (!is_null($request->consigneeTin)) {

//                 $tinLengthConsignee = strlen((string) $request->consigneeTin);

//                 if (
//                     !is_numeric($request->consigneeTin)
//                     || $tinLengthConsignee !== 9
//                 ) {

//                     DB::rollBack();

//                     return response()->json([
//                         'Error' => 'Consignee TIN number should be exactly 9 digits'
//                     ]);
//                 }
//             }
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Route Validation
//         |--------------------------------------------------------------------------
//         */

//         if (empty($request->geofence_reoute_id)) {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Route is required. Please select a valid route'
//             ]);
//         }

//         $route = GeofenceRoute::find($request->geofence_reoute_id);

//         if (!$route) {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Invalid route. Route not found.'
//             ]);
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Device Status Validation
//         |--------------------------------------------------------------------------
//         */

//         if ((string) $device->current_status === "1") {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Device is already activated'
//             ]);
//         }

//         if ($device->power < 50 || $device->power > 100) {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Power should be between 50 and 100 for activation'
//             ]);
//         }

//         if ((string) $device->lockrope === "0") {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Rope is Open'
//             ]);
//         }

//         if ((string) $device->coverstatus === "0") {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Coverstatus is Open'
//             ]);
//         }

//         if ((string) $device->lockstatus === "0") {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Device does not Locking Intact'
//             ]);
//         }


      
//         /*
//         |--------------------------------------------------------------------------
//         | Office Validation
//         |--------------------------------------------------------------------------
//         */

//         $office = Office::where(
//             'office_code',
//             $request->dipartureOffice
//         )->first();

//         if (!$office) {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Departure Office not found.'
//             ]);
//         }

//         $destinationOffice = Office::where(
//             'office_code',
//             $request->destination
//         )->first();

//         if (!$destinationOffice) {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Destination Office not found.'
//             ]);
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Select Geofence
//         |--------------------------------------------------------------------------
//         */

//         $specificDepartureOffices = [
//             'KEMBA',
//             'KESCT',
//             'UGSCT',
//             'TZSCT',
//             'TZDL'
//         ];

//         $alternativeOfficeCodes = [
//             '11KA',
//             '11GA',
//             '11RU',
//             '31CY'
//         ];

//         if (in_array(
//             $request->dipartureOffice,
//             $specificDepartureOffices,
//             true
//         )) {

//             $geofences = Geofence::with('office')
//                 ->whereHas('office', function ($query) use ($alternativeOfficeCodes) {

//                     $query->whereIn(
//                         'office_code',
//                         $alternativeOfficeCodes
//                     );

//                 })
//                 ->get();

//             if ($geofences->isEmpty()) {

//                 DB::rollBack();

//                 return response()->json([
//                     'Error' => 'Alternative geofence not found'
//                 ]);
//             }

//         } else {

//             $geofences = Geofence::with('office')
//                 ->whereHas('office', function ($query) use ($request) {

//                     $query->where(
//                         'office_code',
//                         $request->dipartureOffice
//                     );

//                 })
//                 ->get();

//             if ($geofences->isEmpty()) {

//                 DB::rollBack();

//                 return response()->json([
//                     'Error' => 'Geofence not found for departure office'
//                 ]);
//             }
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Check Device Inside Geofence
//         |--------------------------------------------------------------------------
//         */

//         $deviceLatitude = $device->latitude;
//         $deviceLongitude = $device->longitude;

//         $isInsideGeofence = $this->isDeviceInsideGeofences(
//             $deviceLatitude,
//             $deviceLongitude,
//             $geofences
//         );

//         /*
//         |--------------------------------------------------------------------------
//         | Restricted Offices
//         |--------------------------------------------------------------------------
//         */

//         $restrictedOffices = [
//             '41MU'
//         ];

//         if (
//             in_array(
//                 $request->dipartureOffice,
//                 $restrictedOffices,
//                 true
//             )
//             &&
//             $isInsideGeofence
//         ) {

//             $insideDuration = $this->getMinutesSince(
//                 $device->datetime
//             );

//             if ($insideDuration > 20) {

//                 DB::rollBack();

//                 return response()->json([
//                     'Error' => 'Activation not allowed. Seal has been inside geofence for more than 20 minutes.'
//                 ]);
//             }
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Generate Activation Number
//         |--------------------------------------------------------------------------
//         */

//         $activationNumber = $this->generateUniqueActivationNumber();

//         if (!$activationNumber) {

//             DB::rollBack();

//             return response()->json([
//                 'Error' => 'Failed to generate a unique Activation Number'
//             ]);
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Create Activation
//         |--------------------------------------------------------------------------
//         */

//         $activation = $this->createActivationFromRequest(
//             $request,
//             $device,
//             $activationNumber,
//             $user ? $user->id : null
//         );

//         /*
//         |--------------------------------------------------------------------------
//         | Save T1 Details
//         |--------------------------------------------------------------------------
//         */

//         $this->saveT1DetailsFromRequest(
//             $request,
//             $activation,
//             $activationType
//         );

//         /*
//         |--------------------------------------------------------------------------
//         | Create Outside Geofence Alert
//         |--------------------------------------------------------------------------
//         */

//         if (!$isInsideGeofence) {

//             $this->createOutsideGeofenceAlert(
//                 $device,
//                 $activation
//             );
//         }

//         /*
//         |--------------------------------------------------------------------------
//         | Mark Device As Activated
//         |--------------------------------------------------------------------------
//         */

//         $this->markDeviceAsActivated($device);

//         /*
//         |--------------------------------------------------------------------------
//         | Commit Transaction
//         |--------------------------------------------------------------------------
//         */

//         DB::commit();

//         return response()->json([
//             'message' => 'E seal Activated successfully'
//         ]);

//     } catch (\Throwable $e) {

//         DB::rollBack();

//         report($e);

//         return response()->json([
//             'Error' => 'Failed to Activate e-seal. ' . $e->getMessage()
//         ]);
//     }
// }







// public function SaveActivationWithT1(Request $request)
// {
//     // return response()->json(['Error' => 'Activation UnderMaintence Contact CMC']);

//     $activationNumber = $this->generateUniqueActivationNumber();

//     if (!$activationNumber) {
//         return response()->json(['Error' => 'Failed to generate a unique Activation Number']);
//     }

//     $deviceNumber = trim((string) $request->deviceNumber);

//     if ($deviceNumber === '') {
//         return response()->json(['Error' => 'e-Seal Not Found, Please Check E-Seal Status you want to activate']);
//     }

//     // Validate activation_type
//     $activationType = (int) $request->activation_type;

//     if (!in_array($activationType, [1, 2], true)) {
//         return response()->json(['Error' => 'Invalid activation type']);
//     }

//     try {
//         $user = Auth::user();

//         // --- 1. Validate T1 / Exit Note duplicates ---
//         if ($activationType === 1 && is_array($request->t1Number)) {
//             foreach ($request->t1Number as $t1Number) {
//                 $t1Exists = T1Detail::where('t1_number', $t1Number)
//                     ->whereHas('activation', function ($query) use ($request) {
//                         $query->where('departure_office', $request->dipartureOffice)
//                               ->where('entryyear', $request->entryyear);
//                     })
//                     ->exists();

//                 if ($t1Exists) {
//                     return response()->json(['Error' => 'T1 number is already activated: ' . $t1Number]);
//                 }
//             }
//         }

//         if ($activationType === 2 && $request->exitNoteNo) {
//             $exitNoteExists = T1Detail::where('exit_note_no', $request->exitNoteNo)
//                 ->whereHas('activation', function ($query) use ($request) {
//                     $query->where('departure_office', $request->dipartureOffice);
//                 })
//                 ->exists();

//             if ($exitNoteExists) {
//                 return response()->json(['Error' => 'Exit Note Number is already activated: ' . $request->exitNoteNo]);
//             }
//         }

//         // --- 2. Get device & current message ---
//         $device = DB::table('devices')
//             ->select(
//                 'current_messages.*',
//                 'devices.*',
//                 'received_devices.status as received_status'
//             )
//             ->leftJoin('received_devices', 'devices.id', '=', 'received_devices.device_id')
//             ->leftJoin('current_messages', 'devices.id', '=', 'current_messages.device_id')
//             ->where(function ($query) use ($deviceNumber) {
//                 $query->where('devices.serial_number', 'LIKE', '%' . $deviceNumber)       // full number search
//                       ->orWhere('devices.serial_number', 'LIKE', '%' . substr($deviceNumber, -4)); // last 4 digits
//             })
//             ->first();

//         if (!$device) {
//             return response()->json(['Error' => 'Device not found for the provided serial number']);
//         }

//         // --- 3. Destination / PBW validation ---
//         if ($request->destination === '11PBW' && is_null($request->pbw_id)) {
//             return response()->json(['Error' => 'The Private bonded office field is required.']);
//         }

//         // --- 4. Seal reporting time (last 10 min) ---
//         if (!$this->checkSealReporting($device->datetime)) {
//             return response()->json(['Error' => 'Seal Not Reporting within 10 minutes ago, Check Reporting Time']);
//         }

//         // --- 5. TIN validations (for activation_type = 2) ---
//         if ($activationType === 2) {
//             $tinLengthCA = strlen((string) $request->clearingAgentTin);

//             if (!is_numeric($request->clearingAgentTin) || $tinLengthCA !== 9) {
//                 return response()->json(['Error' => 'Clearing agent TIN number should be exactly 9 digits']);
//             }

//             if (!is_null($request->consigneeTin)) {
//                 $tinLengthConsignee = strlen((string) $request->consigneeTin);

//                 if (!is_numeric($request->consigneeTin) || $tinLengthConsignee !== 9) {
//                     return response()->json(['Error' => 'Consignee TIN number should be exactly 9 digits']);
//                 }
//             }
//         }

//         // --- 6. Route validation ---
//         if (empty($request->geofence_reoute_id)) {
//             return response()->json(['Error' => 'Route is required. Please select a valid route']);
//         }

//         $route = GeofenceRoute::find($request->geofence_reoute_id);

//         if (!$route) {
//             return response()->json(['Error' => 'Invalid route. Route not found.']);
//         }

//         // --- 7. Device status checks ---
//         if ((string) $device->current_status === "1") {
//             return response()->json(['Error' => 'Device is already activated']);
//         }

//         if ($device->power < 50 || $device->power > 100) {
//             return response()->json(['Error' => 'Power should be between 50 and 100 for activation']);
//         }

//         if ((string) $device->lockrope === "0") {
//             return response()->json(['Error' => 'Rope is Open']);
//         }

//         if ((string) $device->coverstatus === "0") {
//             return response()->json(['Error' => 'Coverstatus is Open']);
//         }

//         if ((string) $device->lockstatus === "0") {
//             return response()->json(['Error' => 'Device does not Locking Intact']);
//         }

//         // --- 8. Offices validation ---
//         $office = Office::where('office_code', $request->dipartureOffice)->first();

//         if (!$office) {
//             return response()->json(['Error' => 'Departure Office not found.']);
//         }

//         $destinationOffice = Office::where('office_code', $request->destination)->first();

//         if (!$destinationOffice) {
//             return response()->json(['Error' => 'Destination Office not found.']);
//         }

//         // --- 9. Geofence selection logic ---
//         $specificDepartureOffices = ['KEMBA', 'KESCT', 'UGSCT', 'TZSCT', 'TZDL'];
//         $alternativeOfficeCodes   = ['11KA', '11GA', '11RU', '31CY'];

//         if (in_array($request->dipartureOffice, $specificDepartureOffices, true)) {
//             // Fetch geofences associated with the alternative office codes
//             $geofences = Geofence::with('office')
//                 ->whereHas('office', function ($query) use ($alternativeOfficeCodes) {
//                     $query->whereIn('office_code', $alternativeOfficeCodes);
//                 })
//                 ->get();

//             if ($geofences->isEmpty()) {
//                 return response()->json(['Error' => 'Alternative geofence not found']);
//             }
//         } else {
//             // Fetch geofences for the departure office
//             $geofences = Geofence::with('office')
//                 ->whereHas('office', function ($query) use ($request) {
//                     $query->where('office_code', $request->dipartureOffice);
//                 })
//                 ->get();

//             if ($geofences->isEmpty()) {
//                 return response()->json(['Error' => 'Geofence not found for departure office']);
//             }
//         }

//         // --- 10. Check if device is inside any geofence polygon ---
//         $deviceLatitude  = $device->latitude;
//         $deviceLongitude = $device->longitude;

//         $isInsideGeofence = $this->isDeviceInsideGeofences($deviceLatitude, $deviceLongitude, $geofences);

//         // --- 11. Special rule for departure offices 11MU & 45MS ---
//         // They can activate inside geofence ONLY if inside <= 20 minutes
//         $restrictedOffices = ['41MU'];

//         if (in_array($request->dipartureOffice, $restrictedOffices, true) && $isInsideGeofence) {
//             $insideDuration = $this->getMinutesSince($device->datetime);

//             if ($insideDuration > 20) {
//                 return response()->json([
//                     'Error' => 'Activation not allowed. Seal has been inside geofence for more than 20 minutes.'
//                 ]);
//             }
//         }

//         // --- 12. Create activation ---
//         $activation = $this->createActivationFromRequest(
//             $request,
//             $device,
//             $activationNumber,
//             $user ? $user->id : null
//         );

//         // --- 13. Save T1 details depending on activation type ---
//         $this->saveT1DetailsFromRequest($request, $activation, $activationType);

//         // --- 14. If outside geofence, create alert ---
//         if (!$isInsideGeofence) {
//             $this->createOutsideGeofenceAlert($device, $activation);
//         }

//         // --- 15. Mark device as activated & close received_devices record ---
//         $this->markDeviceAsActivated($device);

//         return response()->json(['message' => 'E seal Activated successfully']);

//     } catch (\Exception $e) {
//         return response()->json(['Error' => 'Failed to Activate e-seal. ' . $e->getMessage()]);
//     }
// }












































}
