<?php

namespace App\Modules\Invoices\controllers\api\v1;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Laravel\Cashier\Stripe;
use Stripe_Charge;
use Illuminate\Support\Facades\Validator;
use App\Modules\Bookings\Task;
use App\Modules\Invoices\InvoiceTransaction;
use Illuminate\Http\Request;
use App\Http\Requests\StoreInvoiceTransactionRequest;
use App\Http\Controllers\BaseController;

class InvoiceTransactionsControllerREST extends BaseController
{
    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        try {
            $transaction = InvoiceTransaction::create($request->all());

            if (!$transaction->id) {
                return response()->json(['errors' => $transaction->errors->all()], 400);
            }

            $transaction->load(['creator', 'invoice']);

            // Update the paid status first
            $transaction->invoice->paid = $transaction->invoice->isPaid();
            $transaction->invoice->save();

            // Sync with Xero - send invoice first if needed, then sync payment
            try {
                $xeroService = app(\App\Modules\Xero\Services\XeroService::class);
                
                // If invoice doesn't have a Xero ID, send it to Xero first
                if (!$transaction->invoice->xeroId) {
                    Log::info('Invoice has no Xero ID, sending invoice to Xero before payment sync', [
                        'transaction_id' => $transaction->id,
                        'invoice_id' => $transaction->invoice_id
                    ]);
                    
                    $xeroService->sendInvoiceToXero($transaction->invoice);
                    
                    // Reload the invoice to get the updated Xero ID
                    $transaction->invoice->refresh();
                }
                
                // Now sync the payment to Xero
                $xeroService->syncPayment($transaction);
                
                Log::info('Payment synced to Xero successfully', [
                    'transaction_id' => $transaction->id,
                    'invoice_id' => $transaction->invoice_id,
                    'xero_invoice_id' => $transaction->invoice->xeroId
                ]);
                
            } catch (\Exception $e) {
                // Log the error but don't fail the transaction
                Log::error('Failed to sync payment to Xero: ' . $e->getMessage(), [
                    'transaction_id' => $transaction->id,
                    'invoice_id' => $transaction->invoice_id
                ]);
            }
        } catch (\Exception $e) {
            Log::error('Failed to create payment transaction: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }

        // Update the related task
        if ($transaction->invoice->task) {
            $transaction->invoice->task->paid = $transaction->invoice->isPaid();
            $transaction->invoice->task->save();
        }

        return $transaction;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        try {
            $transaction = InvoiceTransaction::findOrFail($id);
            $transaction->load('invoice');

            // Delete from Xero if needed
            if ($transaction->xero_id) {
                $xeroService = app(\App\Modules\Xero\Services\XeroService::class);
                $xeroService->deletePayment($transaction->xero_id);
            }

            if (! $transaction->delete()) {
                return response()->json(['errors' => $transaction->errors->all()], 400);
            }

            // Update the paid status
            $transaction->invoice->paid = $transaction->invoice->isPaid();
            $transaction->invoice->save();

            // Update the related task
            if ($transaction->invoice->task) {
                $transaction->invoice->task->paid = $transaction->invoice->isPaid();
                $transaction->invoice->task->save();
            }

            return $transaction;
        } catch (Exception $e) {
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }

    // Removed Kashflow payment methods - using Xero integration instead

    public function onlinePayment(\App\Http\Requests\StoreInvoiceTransactionRequest $request)
    {
        // The api is closed now...
        return [];

        Stripe::setApiKey(Config::get('stripe.api_key'));

        // Retrieve the invoice
        $invoice = Invoice::findOrFail($request->input('invoice_id'));

        try {
            $charge = Stripe_Charge::create([
                'amount'   => $request->input('amount') * 100, // the amount should be converted to pences that's why we multiply it by 100 ( £1.00 == 100 pences )
                'currency' => 'gbp',
                'card'     => [
                        'number'    => $request->input('card_number'),
                        'exp_month' => $request->input('exp_month'),
                        'exp_year'  => $request->input('exp_year'),
                        'cvc'       => $request->input('cvc'),
                    ],
                'description' => $request->input('notes').' Invoice #'.$invoice->invoice_number,
            ]);
        } catch (Exception $e) {
            Log::error($e->getMessage());

            return response()->json(['error' => $e->getMessage()], 400);
        }

        // Store the transaction normally
        return $this->store();
    }
}
