<?php

namespace App\Http\Controllers\API\V4;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Discount;
use Carbon\Carbon;

class DiscountController extends Controller
{
    public function fetchDiscounts(Request $request)
    {
        $key = $request->query('UserKey');
        $lastSyncTime = $request->query('LastSyncTime');

        $user = User::where('id_session', $key)->first();

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

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

        $query = Discount::where('user', $masterUser->phone_number)
                         ->where('active', '0');

        if ($lastSyncTime) {
            $query->where('updated_at', '>', Carbon::parse($lastSyncTime));
        }

        $discounts = $query->orderBy('name_discount', 'asc')->get();

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

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

    public function syncDiscount(Request $request)
    {
        $key = $request->query('UserKey');

        $user = User::where('id_session', $key)->first();
        if (!$user) {
            return response()->json([['status' => 'failed', 'message' => 'Invalid user key']]);
        }

        $data = $request->json()->all();

        $localId = $data['local_id_discount'] ?? null;
        $cloudId = $data['id_discount'] ?? null;
        $updatedAt = $data['updated_at'] ?? null;

        $existing = Discount::where('local_id_discount', $localId)
                    ->orWhere('id_discount', $cloudId)
                    ->first();

        if ($existing) {
            if ($updatedAt && $existing->updated_at >= Carbon::parse($updatedAt)) {
                return response()->json([['status' => 'success']]);
            }

            $existing->update([
                'name_discount' => $data['name_discount'],
                'note' => $data['note'],
                'type' => $data['type'],
                'nominal' => $data['nominal'],
                'local_id_discount' => $localId,
                'updated_at' => $updatedAt
            ]);

            return response()->json([['status' => 'success']]);
        } else {
            Discount::create([
                'local_id_discount' => $localId,
                'id_discount' => $cloudId,
                'name_discount' => $data['name_discount'],
                'note' => $data['note'],
                'type' => $data['type'],
                'nominal' => $data['nominal'],
                'user' => $data['user'],
                'active' => $data['active'],
                'updated_at' => $updatedAt
            ]);

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