<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Http\Controllers\Controller;
use App\Models\RequisitionMaster;
use App\Models\Units;
use App\Models\Warehouse;
use App\Models\Approval;
use App\Service\Shop\RequisitionService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class RequisitionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {

        $warehouses = Warehouse::whereNot('id', Auth::user()->shop_id)->get();

        return Inertia::render('Shops/Requisition', compact('warehouses'));
    }

    public function view(Request $request)
    {
        $purchase_invoice_no = RequisitionMaster::latest()->first();
        $invoice_no = 'R' . Carbon::now()->format('ymd') . '0001';

        if ($purchase_invoice_no) {
            $old_invoice_no = $purchase_invoice_no->invoice_no;

            // Safely check if invoice_no is long enough
            if (strlen($old_invoice_no) >= 11) { // R + 6 date + 4 number
                $date_part = substr($old_invoice_no, 1, 6);  // yymmdd
                $increment_part = substr($old_invoice_no, 7, 4); // 4 digits number

                // Parse date
                try {
                    $oldDate = Carbon::createFromFormat('ymd', $date_part);
                    $currentDate = Carbon::now();

                    if ($currentDate->month == $oldDate->month) {
                        $new_increment = sprintf('%04d', (int) $increment_part + 1);
                        $invoice_no = 'R' . $currentDate->format('ymd') . $new_increment;
                    } else {
                        $invoice_no = 'R' . $currentDate->format('ymd') . '0001';
                    }
                } catch (\Exception $e) {
                    // In case parsing fails, default new invoice
                    $invoice_no = 'R' . Carbon::now()->format('ymd') . '0001';
                }
            }
        }
        
        // Get search term from request
        $search = $request->input('search', '');
        $perPage = $request->input('perPage', 10); // Default 10 items per page
        $page = $request->input('page', 1);
        
        // Purchase Requisition List with search and pagination
        $query = RequisitionMaster::where('shop_id', Auth::user()->shop_id)
            ->with('RequsitionDetailes', 'shop', 'toLocation', 'client', 'branch', 'department', 'contactPerson.designation', 'contactPerson.department')
            ->orderByDesc('id');
        
        // Apply search if provided
        if (!empty($search)) {
            $query->where(function($q) use ($search) {
                $q->where('invoice_no', 'like', "%{$search}%")
                  ->orWhere('status', 'like', "%{$search}%")
                  ->orWhere('requisition_date', 'like', "%{$search}%")
                  ->orWhereHas('client', function($subQuery) use ($search) {
                      $subQuery->where('name', 'like', "%{$search}%")
                              ->orWhere('code', 'like', "%{$search}%");
                  })
                  ->orWhereHas('toLocation', function($subQuery) use ($search) {
                      $subQuery->where('name', 'like', "%{$search}%");
                  });
            });
        }
        
        // Get paginated results
        $purchaseRequsition = $query->paginate($perPage, ['*'], 'page', $page);
        
        // Poduct info
        $category = [];
        $unit = Units::get();
        $product = [];

        return response()->json([
            'invoice_no' => $invoice_no, 
            'requsition' => $purchaseRequsition, 
            'category' => $category, 
            'unit' => $unit, 
            'product' => $product
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {

   
        $requisition = RequisitionService::DataStore(request()->all());
        // Invoice No
        $purchase_invoice_no = RequisitionMaster::latest()->first();
        $invoice_no = 'R' . Carbon::now()->format('ymd') . '0001';
        if ($purchase_invoice_no) {
            $old_invoice_no = $purchase_invoice_no->invoice_no;

            // Safely check if invoice_no is long enough
            if (strlen($old_invoice_no) >= 11) { // R + 6 date + 4 number
                $date_part = substr($old_invoice_no, 1, 6);  // yymmdd
                $increment_part = substr($old_invoice_no, 7, 4); // 4 digits number

                // Parse date
                try {
                    $oldDate = Carbon::createFromFormat('ymd', $date_part);
                    $currentDate = Carbon::now();

                    if ($currentDate->month == $oldDate->month) {
                        $new_increment = sprintf('%04d', (int) $increment_part + 1);
                        $invoice_no = 'R' . $currentDate->format('ymd') . $new_increment;
                    } else {
                        $invoice_no = 'R' . $currentDate->format('ymd') . '0001';
                    }
                } catch (\Exception $e) {
                    // In case parsing fails, default new invoice
                    $invoice_no = 'R' . Carbon::now()->format('ymd') . '0001';
                }
            }
        }
        // Purchase Maker List
        $purchaseRequsition = RequisitionMaster::where('shop_id', Auth::user()->shop_id)->orderbydesc('id')->with('RequsitionDetailes', 'shop', 'toLocation')->get();

        return response()->json([
            'success' => 'Requisition create successfully',
            'requisition_id' => $requisition->id ?? null
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        // For approval preview, allow access by ID regardless of current user's shop
        // (if you need stricter permissions, add them here instead of filtering by shop_id).
        $requisition = RequisitionMaster::where('id', $id)
            ->with([
                'RequsitionDetailes' => function($query) {
                    $query->with('attribute.product', 'attribute.brand', 'attribute.color', 'attribute.size', 'attribute.origin', 'attribute.unit');
                },
                'shop',
                'toLocation',
                'client',
                'branch',
                'department',
                'contactPerson.designation',
                'contactPerson.department',
                'user',
                'approval.assignments.user',
                'approval.history.user'
            ])
            ->firstOrFail();

        // Check if current user has an approval assignment for this requisition
        $userApprovalAssignment = null;
        if ($requisition->approval) {
            $userApprovalAssignment = $requisition->approval->assignments()
                ->where('user_id', Auth::id())
                ->first();
        }

        return Inertia::render('Shops/RequisitionSingleView', [
            'requisition' => $requisition,
            'userApprovalAssignment' => $userApprovalAssignment ? [
                'approval_id' => $requisition->approval->id,
                'assignment_id' => $userApprovalAssignment->id,
                'module_name' => 'Requisition',
                'reference_id' => $requisition->invoice_no,
                'assignment_status' => $userApprovalAssignment->status,
                'is_final' => $userApprovalAssignment->is_final ?? false,
                'has_final_approver' => $requisition->approval->assignments()->where('is_final', true)->exists(),
                'can_reassign' => ($userApprovalAssignment->status === 'approved' && !$userApprovalAssignment->is_final && $requisition->approval->status === 'pending') ||
                                  ($userApprovalAssignment->status === 'pending' && !$userApprovalAssignment->is_final),
                'note' => $requisition->approval->note,
                'history' => $requisition->approval->history->map(function ($h) {
                    return [
                        'action' => $h->action,
                        'user' => $h->user->name ?? 'Unknown',
                        'comment' => $h->comment,
                        'created_at' => $h->created_at->format('Y-m-d H:i:s'),
                    ];
                }),
            ] : null,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        RequisitionService::DataUpdate(request()->all(), $id);
        // Invoice No
        $purchase_invoice_no = RequisitionMaster::latest()->first();
        $invoice_no = 'R' . Carbon::now()->format('ymd') . '0001';

        if ($purchase_invoice_no) {
            $old_invoice_no = $purchase_invoice_no->invoice_no;

            // Safely check if invoice_no is long enough
            if (strlen($old_invoice_no) >= 11) { // R + 6 date + 4 number
                $date_part = substr($old_invoice_no, 1, 6);  // yymmdd
                $increment_part = substr($old_invoice_no, 7, 4); // 4 digits number

                // Parse date
                try {
                    $oldDate = Carbon::createFromFormat('ymd', $date_part);
                    $currentDate = Carbon::now();

                    if ($currentDate->month == $oldDate->month) {
                        $new_increment = sprintf('%04d', (int) $increment_part + 1);
                        $invoice_no = 'R' . $currentDate->format('ymd') . $new_increment;
                    } else {
                        $invoice_no = 'R' . $currentDate->format('ymd') . '0001';
                    }
                } catch (\Exception $e) {
                    // In case parsing fails, default new invoice
                    $invoice_no = 'R' . Carbon::now()->format('ymd') . '0001';
                }
            }
        }

        return response()->json(['success' => 'Requisition Update successfully', ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        RequisitionMaster::find($id)->delete();
        $purchase_invoice_no = RequisitionMaster::latest()->first();
        $invoice_no = 'R' . Carbon::now()->format('ymd') . '0001';

        if ($purchase_invoice_no) {
            $old_invoice_no = $purchase_invoice_no->invoice_no;

            // Safely check if invoice_no is long enough
            if (strlen($old_invoice_no) >= 11) { // R + 6 date + 4 number
                $date_part = substr($old_invoice_no, 1, 6);  // yymmdd
                $increment_part = substr($old_invoice_no, 7, 4); // 4 digits number

                // Parse date
                try {
                    $oldDate = Carbon::createFromFormat('ymd', $date_part);
                    $currentDate = Carbon::now();

                    if ($currentDate->month == $oldDate->month) {
                        $new_increment = sprintf('%04d', (int) $increment_part + 1);
                        $invoice_no = 'R' . $currentDate->format('ymd') . $new_increment;
                    } else {
                        $invoice_no = 'R' . $currentDate->format('ymd') . '0001';
                    }
                } catch (\Exception $e) {
                    // In case parsing fails, default new invoice
                    $invoice_no = 'R' . Carbon::now()->format('ymd') . '0001';
                }
            }
        }
       

        return response()->json(['success' => 'Requisition Delete successfully']);
    }
}
