<?php

namespace App\Http\Controllers;

use App\Models\Bidders;
use App\Models\Checkout;
use App\Models\WinningBids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class NorthCheckoutController extends Controller
{
    public function checkout(Request $request, $bidder_id)
    {
        $bidder = Bidders::where('idbidders', $bidder_id)->firstOrFail();

        // Check if already checked out
        if (Checkout::where('bidder_num', $bidder->idbidders)->exists()) {
            return redirect('/mywinnings?bidder_number=' . $bidder->bidder_assigned_number)->with('error', 'Bidder has already checked out.');
        }

        $winnings = WinningBids::where('winning_bidder_num', $bidder->idbidders)->get();
        $total_cost = $winnings->sum('winning_cost');

        if ($total_cost <= 0) {
            return redirect('/mywinnings?bidder_number=' . $bidder->bidder_assigned_number)->with('error', 'No winnings found for this bidder.');
        }

        return view('north_checkout', [
            'bidder' => $bidder,
            'total_cost' => $total_cost,
        ]);
    }

    public function createSession(Request $request, $bidder_id)
    {
        $bidder = Bidders::findOrFail($bidder_id);
        $winnings = WinningBids::with('items')->where('winning_bidder_num', $bidder->idbidders)->get();
        $total_cost = $winnings->sum('winning_cost');

        $products = $winnings->map(function($winning) {
            return [
                'name' => $winning->items->item_desc ?? 'Auction Item',
                'price' => (float)$winning->winning_cost,
                'quantity' => 1
            ];
        })->toArray();

        $apiKey = config('services.north.private_api_key');
        $checkoutId = config('services.north.checkout_id');
        $profileId = config('services.north.profile_id');

        if (!$apiKey || !$checkoutId || !$profileId) {
            return response()->json(['error' => 'North configuration missing.'], 500);
        }

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $apiKey,
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
        ])->post('https://checkout.north.com/api/sessions', [
            'checkoutId' => $checkoutId,
            'profileId' => $profileId,
            'amount' => (float)$total_cost,
            'products' => $products,
        ]);

        if ($response->failed()) {
            Log::error('North Session Creation Failed: ' . $response->status() . ' ' . $response->body());
            return response()->json([
                'error' => 'Failed to create checkout session: ' . ($response->json('message') ?? 'Unknown error'),
                'status' => $response->status(),
                'body' => $response->body()
            ], 500);
        }

        $data = $response->json();
        
        // If json() is null but body is not empty, it might be a parsing error
        if (is_null($data) && !empty($response->body())) {
             Log::error('North Session Response is not JSON: ' . $response->body());
             return response()->json([
                'error' => 'Response from North is not valid JSON.',
                'raw_body' => $response->body()
            ], 500);
        }

        $token = $data['token'] ?? 
                 $data['sessionToken'] ?? 
                 $data['id'] ?? 
                 $data['session_id'] ?? 
                 ($data['session']['id'] ?? null);

        if (!$token) {
            Log::error('North Session Token Missing in Response: ' . json_encode($data));
            return response()->json([
                'error' => 'Session token not found in API response.',
                'debug_response' => $data,
                'raw_body' => $response->body()
            ], 500);
        }

        return response()->json(['sessionToken' => $token]);
    }

    public function verify(Request $request, $bidder_id)
    {
        $bidder = Bidders::findOrFail($bidder_id);
        $sessionToken = $request->query('sessionToken');
        if (!$sessionToken) {
            return redirect('/mywinnings?bidder_number=' . $bidder->bidder_assigned_number)->with('error', 'Missing session token.');
        }

        $apiKey = config('services.north.private_api_key');
        $checkoutId = config('services.north.checkout_id');
        $profileId = config('services.north.profile_id');

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $apiKey,
            'SessionToken' => $sessionToken,
            'CheckoutId' => $checkoutId,
            'ProfileId' => $profileId,
            'Accept' => 'application/json',
        ])->get('https://checkout.north.com/api/sessions/status');

        if ($response->failed()) {
            Log::error('North Session Verification Failed: ' . $response->status() . ' ' . $response->body());
            return redirect('/mywinnings?bidder_number=' . $bidder->bidder_assigned_number)->with('error', 'Failed to verify payment status. Status: ' . $response->status());
        }

        $status = $response->json();
        $currentStatus = $status['status'] ?? '';

        // The North API status check might return Approved, completed, success, authorized, or captured.
        $successStatuses = ['approved', 'completed', 'success', 'authorized', 'captured'];
        
        if (in_array(strtolower($currentStatus), $successStatuses)) {
             // Check if already checked out to avoid duplicates
             $existingCheckout = Checkout::where('bidder_num', $bidder->idbidders)->first();
             
             if (!$existingCheckout) {
                 // According to docs, when status is Approved, transaction details are in 'body'
                 // Digital wallets might have these at the top level
                 $body = $status['body'] ?? [];
                 $winnertotal = $status['amount'] ?? 
                                ($body['amount'] ?? 
                                ($status['amount_total'] ?? 
                                WinningBids::where('winning_bidder_num', $bidder->idbidders)->sum('winning_cost')));
                                
                 $payment_method = 3; // Credit Card
                 $cc_transaction = $body['auth_guid'] ?? 
                                   ($status['transaction_id'] ?? 
                                   ($status['transactionId'] ?? 
                                   ($status['id'] ?? 'NORTH_EC')));
                                   
                 $cc_amount = $winnertotal;
                 $check_number = null;

                 $checkout_id = DB::table('checkout')->insertGetID(
                    [
                    'bidder_num' => $bidder->idbidders,
                    'winnertotal' => $winnertotal,
                    'payment_method' => $payment_method,
                    'check_number' => $check_number,
                    'cc_transaction' => $cc_transaction,
                    'cc_amount' => $cc_amount,
                    'created_at' => now(),
                    'updated_at' => now(),
                    ]
                 );
             } else {
                 $checkout_id = $existingCheckout->checkout_id;
                 $payment_method = $existingCheckout->payment_method;
                 $cc_transaction = $existingCheckout->cc_transaction;
                 $check_number = $existingCheckout->check_number;
             }

             // Replicate the data for checkout_complete view
             $checkout_list_results = DB::select("SELECT
                *, items.item_assigned_num, items.item_desc
                FROM winning_bids
                INNER JOIN items AS items
                ON winning_bids.winning_item_num=items.iditems
                WHERE winning_bidder_num = $bidder->idbidders
              ");

             $checkout_info_results = DB::select("SELECT
                winning_bids.*,
                bidders.*,
                sum(winning_cost) AS total_cost
                FROM winning_bids
                INNER JOIN bidders AS bidders
                ON winning_bids.winning_bidder_num=bidders.idbidders
                WHERE winning_bidder_num = $bidder->idbidders
                GROUP BY winning_bids.winning_bidder_num
              ");

             return view('checkout_complete', [
               'checkout_result' => $checkout_id,
               'checkout_list_results' => $checkout_list_results,
               'checkout_info_results' => $checkout_info_results,
               'payment_method' => $payment_method,
               'check_number' => $check_number,
               'cc_transaction' => $cc_transaction
             ]);
        }

        return redirect('/mywinnings?bidder_number=' . $bidder->bidder_assigned_number)->with('error', 'Payment not completed. Status: ' . ($status['status'] ?? 'unknown'));
    }
}
