<?php

namespace App\Http\Controllers\API\V4;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\FcmHelper;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class SalesController extends Controller
{
    /**
     * Fetch sales data for a specific user based on UserKey and LastSyncTime
     */
    public function fetchSalesData(Request $request)
    {
        $userKey = $request->query('UserKey');
        $lastSyncTime = $request->query('LastSyncTime');

        if (empty($userKey)) {
            return response()->json([
                'status' => 'false',
                'errCode' => '00',
                'msg' => 'UserKey is required',
                'data' => []
            ]);
        }

        $user = DB::table('users')->where('id_session', $userKey)->first();

        if (!$user) {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'User Not Found',
                'data' => []
            ]);
        }

        // Build base query depending on user level
        $query = DB::table('sales_data');

        if ($user->level === 'master') {
            $query->where('id_store', $user->id_store);
        } else {
            $query->where('operator', $user->phone_number);
        }

        if ($lastSyncTime && $lastSyncTime > 1) {
            $query->where('updated_at', '>', $lastSyncTime);
        }

        $salesData = $query->orderByDesc('id_sales_data')->get();

        if ($salesData->isEmpty()) {
            return response()->json([
                'status' => 'true',
                'errCode' => '02',
                'msg' => 'No Sales Found',
                'data' => []
            ]);
        }

        // Format response data exactly as in original code
        $response = $salesData->map(function ($data) {
            return [
                'local_id_sales_data'     => $data->local_id_sales_data,
                'cloud_id_sales_data'     => $data->id_sales_data,
                'user'                   => $data->user,
                'shift'                  => $data->shift,
                'id_customer'            => $data->id_customer ?? 1,
                'id_store'               => $data->id_store,
                'no_invoice'             => $data->no_invoice,
                'date'                   => $data->date,
                'payment'                => $data->payment,
                'paymentstatus'          => $data->paymentstatus,
                'note'                   => $data->note,
                'totalorder'             => $data->totalorder,
                'totalprice'             => $data->totalprice,
                'totalpay'               => $data->totalpay ?? 0.0,
                'changepay'              => $data->changepay ?? 0.0,
                'status'                 => $data->status,
                'due_date'               => $data->due_date,
                'tax'                    => $data->tax ?? 0.0,
                'discount'               => $data->discount ?? 0.0,
                'id_discount'            => $data->id_discount,
                'service_charge'         => $data->service_charge ?? 0.0,
                'operator'               => $data->operator,
                'location'               => $data->location,
                'id_table'               => $data->id_table,
                'time'                   => $data->time,
                'expected_delivery_time' => $data->expected_delivery_time,
                'delivery_price'         => $data->delivery_price ?? 0.0,
                'serviceby'              => $data->serviceby,
                'updated_at'             => $data->updated_at,
            ];
        });

        return response()->json($response);
    }

    /**
     * Insert or update sales data via POST request
     */
    public function syncSalesData(Request $request)
    {
        $userKey = $request->query('UserKey');

        if (empty($userKey)) {
            return response()->json([
                'status' => 'false',
                'errCode' => '00',
                'msg' => 'UserKey is required',
                'data' => []
            ], 400);
        }

        // Validate required fields if needed here, or assume data is provided in request JSON

        // Get user and master user for 'user' field
        $user = DB::table('users')->where('id_session', $userKey)->first();

        if (!$user) {
            return response()->json([
                'status' => 'false',
                'errCode' => '00',
                'msg' => 'User Not Found',
                'data' => []
            ], 404);
        }

        $masterUser = DB::table('users')->where('phone_number', $user->master)->first();

        $input = $request->all();

        // Prepare fields with defaults or fallback values
        $dueDate = !empty($input['due_date']) ? $input['due_date'] : ($input['date'] ?? null);
        $discount = $input['discount'] ?? 0.0;
        $idCustomer = !empty($input['id_customer']) ? $input['id_customer'] : 1;
        $expectedDeliveryTime = !empty($input['expected_delivery_time']) ? $input['expected_delivery_time'] : ($input['date'] ?? null);

        // Check if sales data with this invoice exists
        $existingSale = DB::table('sales_data')->where('no_invoice', $input['no_invoice'])->first();

        if ($existingSale) {
            // If updated_at is provided, compare timestamps
            if (!empty($input['updated_at'])) {
                if ($existingSale->updated_at >= $input['updated_at']) {
                    // Existing record is newer or equal; discard update
                    return response()->json([["status" => "success"]]);
                } else {
                    // Update the existing record
                    DB::table('sales_data')
                        ->where('no_invoice', $input['no_invoice'])
                        ->update([
                            'id_customer' => $idCustomer,
                            'no_invoice' => $input['no_invoice'],
                            'local_id_sales_data' => $input['local_id_sales_data'],
                            'date' => $input['date'],
                            'time' => $input['time'],
                            'id_store' => $input['id_store'],
                            'payment' => $input['payment'],
                            'totalorder' => $input['totalorder'],
                            'totalpay' => $input['totalpay'],
                            'totalprice' => $input['totalprice'],
                            'changepay' => $input['changepay'],
                            'status' => $input['salestatus'],
                            'due_date' => $dueDate,
                            'operator' => $input['operator'],
                            'tax' => $input['tax'],
                            'discount' => $discount,
                            'id_discount' => $input['id_discount'],
                            'service_charge' => $input['service_charge'],
                            'note' => "",
                            'location' => "",
                            'shift' => $input['shift'],
                            'expected_delivery_time' => $expectedDeliveryTime,
                            'id_table' => $input['id_table'],
                            'user' => $masterUser->phone_number ?? null,
                            'paymentstatus' => $input['paymentstatus'],
                            'delivery_price' => $input['delivery_price'],
                            'updated_at' => $input['updated_at'],
                            'serviceby' => $input['serviceby'] ?? null,
                        ]);

                    return response()->json([["status" => "success"]]);
                }
            } else {
                // No updated_at provided, do nothing (keep existing)
                return response()->json([["status" => "success"]]);
            }
        } else {
            // Insert new sales record
            DB::table('sales_data')->insert([
                'id_customer' => $idCustomer,
                'no_invoice' => $input['no_invoice'],
                'local_id_sales_data' => $input['local_id_sales_data'],
                'date' => $input['date'],
                'time' => $input['time'],
                'id_store' => $input['id_store'],
                'payment' => $input['payment'],
                'totalorder' => $input['totalorder'],
                'totalpay' => $input['totalpay'],
                'totalprice' => $input['totalprice'],
                'changepay' => $input['changepay'],
                'status' => $input['salestatus'],
                'due_date' => $dueDate,
                'operator' => $input['operator'],
                'tax' => $input['tax'],
                'discount' => $discount,
                'id_discount' => $input['id_discount'],
                'service_charge' => $input['service_charge'],
                'note' => "",
                'location' => "",
                'shift' => $input['shift'],
                'expected_delivery_time' => $expectedDeliveryTime,
                'id_table' => $input['id_table'],
                'user' => $masterUser->phone_number ?? null,
                'paymentstatus' => $input['paymentstatus'],
                'delivery_price' => $input['delivery_price'],
                'updated_at' => $input['updated_at'],
                'serviceby' => $input['serviceby'] ?? null,
            ]);

           // 🔔 notify the master
            $this->sendNotificationToMaster($user);

            return response()->json([["status" => "success"]]);
        }
    }

      // GET /getDataSales?UserKey=...&LastSyncTime=...
    public function fetchSales(Request $request)
    {
        $userKey = $request->query('UserKey');
        $lastSyncTime = $request->query('LastSyncTime');

        if (empty($userKey)) {
            return response()->json([
                'status' => 'false',
                'errCode' => '00',
                'msg' => 'UserKey is required',
                'data' => []
            ]);
        }

        // Fetch user
        $user = DB::table('users')->where('id_session', $userKey)->first();

        if (!$user) {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'User Not Found',
                'data' => []
            ]);
        }

        // Fetch master account
        $master = DB::table('users')->where('phone_number', $user->master)->first();

        // Build sales query depending on user level
        if ($user->level === 'admin') {
            $salesQuery = DB::table('sales')->where('id_store', $user->id_store);
        } elseif ($user->level === 'master') {
            $salesQuery = DB::table('sales')->where('user', $master->phone_number);
        } else {
            $salesQuery = DB::table('sales as s')
                ->join('sales_data as sd', 's.no_invoice', '=', 'sd.no_invoice')
                ->where('sd.operator', $user->phone_number)
                ->select('s.*');
        }

        if ($lastSyncTime && $lastSyncTime > 1) {
            $salesQuery->where('updated_at', '>', $lastSyncTime);
        }

        $salesQuery->orderBy('updated_at', 'desc');

        $sales = $salesQuery->get();

        if ($sales->isEmpty()) {
            return response()->json([
                'status' => 'true',
                'errCode' => '02',
                'msg' => 'No Sales Found',
                'data' => []
            ]);
        }

        // Format response
        $response = $sales->map(function ($sale) {
            return [
                'local_id_sales' => $sale->local_id_sales,
                'cloud_id_sales' => $sale->cloud_id_sales ?? null,
                'id_customer' => $sale->id_customer,
                'id_store' => $sale->id_store,
                'id_product' => $sale->id_product,
                'no_invoice' => $sale->no_invoice,
                'amount' => $sale->amount,
                'price' => $sale->price,
                'user' => $sale->user,
                'date' => $sale->date,
                'totalprice' => $sale->totalprice,
                'note' => $sale->note,
                'totalcapital' => $sale->totalcapital,
                'rest_stock' => $sale->rest_stock,
                'status' => $sale->status,
                'updated_at' => $sale->updated_at,
            ];
        });

        return response()->json($response);
    }

    // POST /postDataSales?UserKey=...
    public function syncSales(Request $request)
    {
        $userKey = $request->query('UserKey');
        if (empty($userKey)) {
            return response()->json(['status' => 'false', 'msg' => 'UserKey is required']);
        }

        $user = DB::table('users')->where('id_session', $userKey)->first();

        if (!$user) {
            return response()->json(['status' => 'false', 'msg' => 'Invalid UserKey']);
        }

        $master = DB::table('users')->where('phone_number', $user->master)->first();

        $input = $request->all();

        // Use null coalescing or default values for fields like note, status, etc.
        $localId = $input['local_id_sales'] ?? null;
        $cloudId = $input['cloud_id_sales'] ?? '0';
        $idCustomer = $input['id_customer'] ?? null;
        $idProduct = $input['id_product'] ?? null;
        $idStore = $input['id_store'] ?? null;
        $userPhone = $master->phone_number ?? null;
        $noInvoice = $input['no_invoice'] ?? null;
        $amount = $input['amount'] ?? 0;
        $price = $input['price'] ?? 0;
        $totalPrice = $input['totalprice'] ?? 0;
        $totalCapital = $input['totalcapital'] ?? 0;
        $date = $input['date'] ?? null;
        $status = $input['status'] ?? 'status';
        $note = $input['note'] ?? 'note';
        $restStock = $input['rest_stock'] ?? 1;
        $updatedAt = $input['updated_at'] ?? null;

        // Check if sale exists by local_id or cloud_id
        $existingSale = DB::table('sales')
            ->where('local_id_sales', $localId)
            ->orWhere('id_sales', $cloudId)
            ->first();

        if ($existingSale) {
            if ($updatedAt && $existingSale->updated_at >= $updatedAt) {
                // Existing record is more recent or same timestamp - do not update
                return response()->json([["status" => "success"]]);
            }

            // Update existing record
            DB::table('sales')
                ->where('local_id_sales', $localId)
                ->orWhere('id_sales', $cloudId)
                ->update([
                    'local_id_sales' => $localId,
                    'id_product' => $idProduct,
                    'amount' => $amount,
                    'id_customer' => $idCustomer,
                    'user' => $userPhone,
                    'no_invoice' => $noInvoice,
                    'status' => $status,
                    'price' => $price,
                    'totalprice' => $totalPrice,
                    'date' => $date,
                    'note' => $note,
                    'rest_stock' => 1,
                    'totalcapital' => $totalCapital,
                    'updated_at' => $updatedAt,
                ]);
        } else {
            // Insert new record
            DB::table('sales')->insert([
                'local_id_sales' => $localId,
                'id_product' => $idProduct,
                'amount' => $amount,
                'id_customer' => $idCustomer,
                'id_store' => $idStore,
                'user' => $userPhone,
                'no_invoice' => $noInvoice,
                'status' => $status,
                'price' => $price,
                'totalprice' => $totalPrice,
                'date' => $date,
                'note' => $note,
                'rest_stock' => 1,
                'totalcapital' => $totalCapital,
                'updated_at' => $updatedAt,
            ]);
        }

        return response()->json([["status" => "success"]]);
    }


    private function sendNotificationToMaster($staffUser)
{
    // Get master (admin) user
   // $masterUser = DB::table('users')->where('phone_number', $staffUser->master)->first();

  //  if (!$masterUser || !$masterUser->fcm_token) return;

    // Prepare FCM payload
    $data = [
        'to' => $staffUser->fcm_token,
        'notification' => [
            'title' => 'New Sale Recorded',
            'body' => $staffUser->name . ' has just recorded a sale.',
            'sound' => 'default',
        ],
        'data' => [
            'type' => 'sale',
            'by' => $staffUser->phone_number,
        ]
    ];

    // Send via FCM HTTP v1 legacy API
    $response = Http::withHeaders([
        'Authorization' => 'key=' . env('FCM_SERVER_KEY'),
        'Content-Type' => 'application/json',
    ])->post('https://fcm.googleapis.com/fcm/send', $data);

    // Optional: Log the response
    \Log::info('FCM Notification Sent: ' . $response->body());
}
}
