<?php

namespace App\Http\Controllers;

use App\Models\ItemRequestCancellation;
use App\Models\ItemRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ItemRequestCancellationsController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = ItemRequestCancellation::select('t_item_request_cancellations.*')
                ->with(['itemRequest.store', 'requestedBy', 'approvedBy']);

            // Searching
            if ($request->has('search') && $request->search['value'] != '') {
                $search = $request->search['value'];
                $query->where(function ($q) use ($search) {
                    $q->whereHas('itemRequest', function ($sq) use ($search) {
                        $sq->where('spb_number', 'ilike', "%{$search}%");
                    })
                    ->orWhereHas('requestedBy', function ($rq) use ($search) {
                        $rq->where('fullname', 'ilike', "%{$search}%");
                    })
                    ->orWhere('reason', 'ilike', "%{$search}%")
                    ->orWhere('status', 'ilike', "%{$search}%");
                });
            }

            // Filter by status
            if ($request->has('status_filter') && $request->status_filter != '') {
                $query->where('status', $request->status_filter);
            }

            $total = $query->count();

            // Sorting
            $columns = ['id', 'item_request_id', 'requested_by', 'requested_at', 'status', 'approved_at'];
            $orderColumn = $columns[$request->order[0]['column']] ?? 'requested_at';
            $orderDir = $request->order[0]['dir'] ?? 'desc';

            $query->orderBy($orderColumn, $orderDir);

            // Pagination
            $start = $request->start;
            $length = $request->length;
            $data = $query->skip($start)->take($length)->get();

            // Format data
            $result = [];
            $no = $start + 1;
            foreach ($data as $row) {
                $statusBadge = $row->status == 'Pending' ? 'badge-secondary' : 
                              ($row->status == 'Approved' ? 'badge-success' : 'badge-danger');
                
                $actions = '<a href="' . route('item_request_cancellations.show', $row->id) . '" class="btn btn-sm btn-info">View</a>';
                
                if ($row->isPending()) {
                    $actions .= ' <button class="btn btn-sm btn-success approve-cancellation" data-id="' . $row->id . '">Approve</button>';
                    $actions .= ' <button class="btn btn-sm btn-danger reject-cancellation" data-id="' . $row->id . '">Reject</button>';
                }
                
                $result[] = [
                    $no++,
                    '<a href="' . route('item_requests.show', $row->itemRequest->id) . '">' . $row->itemRequest->spb_number . '</a>',
                    $row->itemRequest->store->name ?? '',
                    $row->requestedBy->fullname ?? '',
                    $row->requested_at->format('d M Y H:i'),
                    '<span class="badge ' . $statusBadge . '">' . $row->status . '</span>',
                    $row->approved_at ? $row->approved_at->format('d M Y H:i') : '-',
                    $row->approvedBy->fullname ?? '-',
                    $actions
                ];
            }

            return response()->json([
                "draw" => intval($request->draw),
                "recordsTotal" => $total,
                "recordsFiltered" => $total,
                "data" => $result,
            ]);
        }

        return view('t-item-request-cancellations.index', [
            'variables' => $this->variables()
        ]);
    }

    public function show(ItemRequestCancellation $itemRequestCancellation)
    {
        $itemRequestCancellation->load(['itemRequest.store', 'requestedBy', 'approvedBy']);
        $variables['judul'] = 'View SPB Cancellation Request';
        
        return view('t-item-request-cancellations.show', [
            'data' => $itemRequestCancellation,
            'variables' => $this->variables($variables)
        ]);
    }

    public function requestCancellation(Request $request)
    {
        $request->validate([
            'item_request_id' => 'required|exists:t_item_requests,id',
            'reason' => 'required|string|min:10',
        ]);

        $itemRequest = ItemRequest::findOrFail($request->item_request_id);

        // Business rule validation
        if (!$itemRequest->canBeCancelled()) {
            return response()->json([
                'success' => false, 
                'message' => 'SPB cannot be cancelled in current status: ' . $itemRequest->status
            ]);
        }

        // Check if there's already a pending cancellation request
        $existingRequest = ItemRequestCancellation::where('item_request_id', $itemRequest->id)
            ->where('status', ItemRequestCancellation::STATUS_PENDING)
            ->first();

        if ($existingRequest) {
            return response()->json([
                'success' => false, 
                'message' => 'There is already a pending cancellation request for this SPB'
            ]);
        }

        try {
            DB::beginTransaction();

            // Create cancellation request
            $cancellation = ItemRequestCancellation::create([
                'item_request_id' => $itemRequest->id,
                'requested_by' => $this->logged_user_id,
                'requested_at' => now(),
                'reason' => $request->reason,
                'status' => ItemRequestCancellation::STATUS_PENDING,
                'created_by' => $this->logged_user_id,
            ]);

            // Update SPB status to Cancellation_Requested
            $itemRequest->update([
                'status' => ItemRequest::STATUS_CANCELLATION_REQUESTED,
                'cancellation_status' => 'Pending',
            ]);

            DB::commit();

            return response()->json([
                'success' => true, 
                'message' => 'Cancellation request submitted successfully',
                'cancellation_id' => $cancellation->id
            ]);

        } catch (\Exception $e) {
            DB::rollback();
            return response()->json([
                'success' => false, 
                'message' => 'Error submitting cancellation request: ' . $e->getMessage()
            ]);
        }
    }

    public function approveCancellation(Request $request)
    {
        $request->validate([
            'cancellation_id' => 'required|exists:t_item_request_cancellations,id',
            'approval_notes' => 'nullable|string',
        ]);

        $cancellation = ItemRequestCancellation::findOrFail($request->cancellation_id);

        if (!$cancellation->isPending()) {
            return response()->json([
                'success' => false, 
                'message' => 'Cancellation request is not pending'
            ]);
        }

        try {
            DB::beginTransaction();

            $cancellation->approve($this->logged_user_id, $request->approval_notes);

            DB::commit();

            return response()->json([
                'success' => true, 
                'message' => 'Cancellation request approved successfully'
            ]);

        } catch (\Exception $e) {
            DB::rollback();
            return response()->json([
                'success' => false, 
                'message' => 'Error approving cancellation: ' . $e->getMessage()
            ]);
        }
    }

    public function rejectCancellation(Request $request)
    {
        $request->validate([
            'cancellation_id' => 'required|exists:t_item_request_cancellations,id',
            'approval_notes' => 'required|string|min:5',
        ]);

        $cancellation = ItemRequestCancellation::findOrFail($request->cancellation_id);

        if (!$cancellation->isPending()) {
            return response()->json([
                'success' => false, 
                'message' => 'Cancellation request is not pending'
            ]);
        }

        try {
            DB::beginTransaction();

            $cancellation->reject($this->logged_user_id, $request->approval_notes);

            DB::commit();

            return response()->json([
                'success' => true, 
                'message' => 'Cancellation request rejected successfully'
            ]);

        } catch (\Exception $e) {
            DB::rollback();
            return response()->json([
                'success' => false, 
                'message' => 'Error rejecting cancellation: ' . $e->getMessage()
            ]);
        }
    }

    private function variables($variables = null)
    {
        $variables['header_routes'] = ' 
								<li class="breadcrumb-item">Transaction</li>  
								<li class="breadcrumb-item active">SPB Cancellation Requests</li>
							 ';
        return $variables;
    }
}