<?php

namespace App\Http\Controllers;

   use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CashCollectionController extends Controller
{
    /**
     * Display a listing of cash collection history.
     *
     * @return \Illuminate\View\View|\Illuminate\Http\JsonResponse
     */
public function index(Request $request)
{
    // Get the authenticated user
    $user = Auth::user();

    // Ensure the user is authenticated and has a 'user_id'
    if (!$user || !$user->user_id) {
        return response()->json(['error' => 'Unauthorized or no delivery agent assigned'], 403);
    }

    // Fetch cash collection history for the authenticated user's user_id
    $cashCollectionHistory = DB::table('cash_collection_history')
        ->where('delivery_agent_id', $user->user_id)
        ->get();

    // Transform and group the data by date
    $groupedData = $cashCollectionHistory->groupBy(function ($item) {
        return \Carbon\Carbon::parse($item->transaction_date)->format('Y-m-d');
    });

    // Prepare the final response structure
    $formattedData = [];
    foreach ($groupedData as $date => $transactions) {
        // Format the date
        $formattedDate = \Carbon\Carbon::parse($date)->isToday()
            ? 'Today'
            : \Carbon\Carbon::parse($date)->format('M d, Y');

        $pickups = $transactions->map(function ($transaction) {
            return [
                'order_id' => $transaction->order_id,
                'amount' => $transaction->amount,
                'transaction_time' => $transaction->transaction_date,
            ];
        });

        $formattedData[] = [
            'date' => $formattedDate,
            'delivery' => $pickups,
        ];
    }

    // Return the response as JSON
    return response()->json(['deliveries' => $formattedData]);
}



    /**
     * Store a newly created cash collection history record.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */

public function store(Request $request)
{
    // Validate the incoming data (only order_id and delivery_agent_id)
    $validated = $request->validate([
        'delivery_agent_id' => 'required|string',
        'order_id' => 'required|integer',
    ]);

    // Get the authenticated user
    $user = Auth::user();

    // Check if the user is authenticated and if the role is 'driver'
    if (!$user || $user->role !== 'driver') {
        return response()->json(['error' => 'Unauthorized, only drivers can perform this action'], 403);
    }

    // Fetch the order details to get the user_total_cost, payment_mode, and check if the order exists
    $order = DB::table('orders')->where('id', $validated['order_id'])->first();

    // If the order does not exist, return an error response
    if (!$order) {
        return response()->json(['message' => 'Order not found'], 404);
    }

    // Check if the payment mode is cash; if not, return an error response
    if ($order->payment_mode !== 'cash') {
        return response()->json(['message' => 'Cash collection is only allowed for orders with cash payment mode'], 400);
    }

    // Check if the order_id already exists in cash_collection_history to prevent duplicates
    $existingCashCollection = DB::table('cash_collection_history')
        ->where('order_id', $validated['order_id'])
        ->first();

    // If the order_id already exists in cash_collection_history, return an error response
    if ($existingCashCollection) {
        return response()->json(['message' => 'Cash collection for this order has already been recorded'], 400);
    }

    // Get the user_total_cost from the order
    $amount = $order->user_total_cost;  // Assuming 'user_total_cost' exists in the 'orders' table

    // If delivery_agent_id is null in the order, update it with the provided delivery_agent_id
    if (!$order->delivery_agent_id) {
        DB::table('orders')
            ->where('id', $validated['order_id'])
            ->update([
                'delivery_agent_id' => $validated['delivery_agent_id'],  // Update delivery agent ID
                'updated_at' => now(),
            ]);
    }

    // Insert new record into the cash_collection_history table
    $id = DB::table('cash_collection_history')->insertGetId([
        'delivery_agent_id' => $validated['delivery_agent_id'],
        'amount' => $amount,  // Use the fetched user_total_cost as the amount
        'transaction_date' => Carbon::now('Asia/Kolkata')->format('Y-m-d H:i:s'),  // Use the correct timezone
        'order_id' => $validated['order_id'],
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    // Update order status to 'Completed' and add timestamp for completion
    $statusTimestamps = json_decode($order->status_timestamps, true) ?? [];
    $currentTimestamp = Carbon::now('Asia/Kolkata')->format('Y-m-d H:i:s');
    $statusTimestamps['Completed'] = $currentTimestamp;

    // Update order status and timestamps
    DB::table('orders')
        ->where('id', $validated['order_id'])
        ->update([
            'status' => 'Completed',
            'status_timestamps' => json_encode($statusTimestamps),
            'updated_at' => now(),
        ]);

    // Return success response
    return response()->json([
        'id' => $id,
        'message' => 'Cash collection history created and order marked as completed successfully.',
    ], 201);
}





    /**
     * Update an existing cash collection history record.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        // Validate the incoming data
        $validated = $request->validate([
            'amount' => 'sometimes|numeric',
            'transaction_date' => 'sometimes|date',
            'order_id' => 'sometimes|integer',
        ]);

        // Update the specified record in the cash_collection_history table
        DB::table('cash_collection_history')->where('id', $id)->update([
            'amount' => $request->input('amount', DB::raw('amount')),
            'transaction_date' => $request->input('transaction_date', DB::raw('transaction_date')),
            'order_id' => $request->input('order_id', DB::raw('order_id')),
            'updated_at' => now(),
        ]);

        return response()->json(['message' => 'Cash collection history updated successfully.']);
    }

    /**
     * Remove a cash collection history record.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        // Delete the specified record from the cash_collection_history table
        DB::table('cash_collection_history')->where('id', $id)->delete();

        return response()->json(['message' => 'Cash collection history deleted successfully.']);
    }
}
