<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Offer;
use App\Models\Operator;
use App\Models\Category;
use App\Models\Order;
use App\Services\VoucherTransactionService;
use App\Support\OfferProjectState;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class OfferController extends Controller
{
    // অফার লিস্ট + ফিল্টার
    public function index(Request $request)
    {
        $offerState = OfferProjectState::resolveRuntimeState();

        if (!$offerState['enabled']) {
            return view('offers.closed', compact('offerState'));
        }

        $operators = Operator::all();
        $categories = Category::all();

        $offers = Offer::query()
            ->when($request->operator_id, function ($query) use ($request) {
                return $query->where('operator_id', $request->operator_id);
            })
            ->when($request->category_id, function ($query) use ($request) {
                return $query->where('category_id', $request->category_id);
            })
            ->get();

        return view('offers.index', compact('offers', 'operators', 'categories'));
    }

    // Buy Now অর্ডার প্রসেস
    public function buy(Request $request, $id)
    {
        $offerState = OfferProjectState::resolveRuntimeState();
        if (!$offerState['enabled']) {
            $msg = (string) ($offerState['notice'] ?? OfferProjectState::DEFAULT_NOTICE);
            if (!empty($offerState['reopen_at'])) {
                $msg .= ' পুনরায় চালু হবে: ' . OfferProjectState::formatForDisplay($offerState['reopen_at']);
            }

            return back()->with('error', $msg);
        }

        $user = Auth::user();
        $offer = Offer::findOrFail($id);

        $request->validate([
            'mobile_number' => ['required', 'string', 'max:20'],
            'password' => ['required', 'string', 'min:6'],
        ], [
            'password.required' => 'অফার ক্রয় করতে পাসওয়ার্ড দিন।',
        ]);

        if (!Hash::check((string) $request->input('password'), (string) $user->password)) {
            return back()
                ->with('error', 'ভুল পাসওয়ার্ড।')
                ->withInput($request->except('password'));
        }

        if ($user->voucher_balance < $offer->price) {
            return back()->with('error', 'আপনার ভাউচার ব্যালেন্স পর্যাপ্ত নয়!');
        }

        // ব্যালেন্স থেকে কাটা
        $beforeVoucher = (float) $user->voucher_balance;
        $debitAmount = (float) $offer->price;
        $afterVoucher = $beforeVoucher - $debitAmount;

        $user->voucher_balance = $afterVoucher;
        $user->save();

        // অর্ডার তৈরি
        $order = Order::create([
            'user_id'       => $user->id,
            'offer_id'      => $offer->id,
            'mobile_number' => $request->mobile_number,
            'status'        => 'pending'
        ]);

        VoucherTransactionService::record(
            userId: (int) $user->id,
            direction: 'debit',
            amount: $debitAmount,
            before: $beforeVoucher,
            after: $afterVoucher,
            source: 'drive_offer_order_debit',
            description: 'ড্রাইভ অফার অর্ডার #' . $order->id . ' করার সময় ভাউচার থেকে কাটা হয়েছে।',
            referenceType: 'offer_order',
            referenceId: $order->id,
            metadata: [
                'offer_id' => $offer->id,
                'mobile_number' => $request->mobile_number,
            ]
        );

        return back()
            ->with('success', 'অর্ডার সফলভাবে গ্রহণ করা হয়েছে। অ্যাডমিন অনুমোদনের জন্য অপেক্ষা করুন।')
            ->with('order_success', [
                'datetime'      => now()->format('d M Y, h:i A'),
                'order_id'      => $order->id,
                'offer_title'   => $offer->title,
                'mobile_number' => $request->mobile_number,
                'price'         => (float) $offer->price,
                'cashback'      => (float) ($offer->cashback ?? 0),
                'status'        => 'Pending',
            ]);
    }

    public function userHistory()
    {
        $orders = Order::where('user_id', auth()->id())->with('offer')->latest()->get();
        return view('orders.history', compact('orders'));
    }
}
