<?php

namespace App\Http\Controllers\Sales;

use App\Constants\ActivityTypes;
use App\Enums\PropertyStatus;
use App\Enums\SeveritySystemLog;
use App\Http\Controllers\Controller;
use App\Http\Messages\ErrorMessages;
use App\Http\Messages\SuccessMessages;
use App\Http\Requests\Sales\UpdatePaymentPlansRequest;
use App\Http\Resources\Realty\PaymentPlansResource;
use App\Http\Responses\ApiResponse;
use App\Services\BitacoraService;
use App\Services\Opportunity\OpportunityService;
use App\Services\Opportunity\ProcedureOpportunityService;
use App\Services\Property\PropertyService;
use App\Services\Sale\PaymentPlanService;
use App\Services\Sale\SaleService;
use App\Services\SystemLogService;
use Illuminate\Support\Facades\DB;

class PaymetPlanController extends Controller
{
    protected $saleService;
    protected $paymentPlansService;
    protected $procedureOpportunityService;
    protected $propertiesService;
    protected $opportunityService;
    protected $bitacoraService;
    protected $systemLogService;

    public function __construct(
        SaleService $saleService,
        PaymentPlanService $paymentPlansService,
        ProcedureOpportunityService $procedureOpportunityService,
        PropertyService $propertiesService,
        OpportunityService $opportunityService,
        BitacoraService $bitacoraService,
        SystemLogService $systemLogService
    ) {
        $this->saleService = $saleService;
        $this->paymentPlansService = $paymentPlansService;
        $this->procedureOpportunityService = $procedureOpportunityService;
        $this->propertiesService = $propertiesService;
        $this->opportunityService = $opportunityService;
        $this->bitacoraService = $bitacoraService;
        $this->systemLogService = $systemLogService;
    }

    /**
     * @OA\Post(
     *     path="/api/sale/paymentPlans/{id}",
     *     summary="Register a Payment Plan",
     *     tags={"Payment Plans"},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         description="ID of the payment plan to confirm",
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             @OA\Property(property="opportunity_id", type="integer", example="1", description="The ID of the related opportunity"),
     *             @OA\Property(property="property_id", type="integer", example="1", description="The ID of the related property"),
     *             @OA\Property(property="sales_id", type="integer", example="1", description="The ID of the related sale"),
     *             @OA\Property(property="amountPaid", type="number", format="float", example="30000", description="The amount being paid in this transaction"),
     *             @OA\Property(
     *                 property="dividedPayments",
     *                 type="array",
     *                 description="Array of remaining divided payment amounts, if applicable",
     *                 @OA\Items(type="number", example="10000")
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=201,
     *         description="Payment Plan confirmed successfully",
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="Invalid request",
     *     ),
     *     @OA\Response(
     *         response=422,
     *         description="Validation error",
     *     )
     * )
     */

    // public function register($id, PaymentPlansConfirmedRequest $request)
    // {
    //     try {
    //         DB::transaction(function () use ($id, $request) {
    //             $this->paymentPlansService->confirmPayment(
    //                 $id,
    //                 $request->input('amountPaid'),
    //                 $request->input('dividedPayments', [])
    //             );
    //         });
    //         $sales = $this->saleService->getSalebyId($request->input('sales_id'));
    //         return ApiResponse::success(SuccessMessages::CREATE_SUCCESS, $sales->payment_plans, [], 201);
    //     } catch (\Exception $e) {
    //         return ApiResponse::error(ErrorMessages::BAD_REQUEST, $e->getMessage(), [], $e->getCode());
    //     }
    // }

    /**
     * @OA\Patch(
     *     path="/api/sale/paymentPlans/{id}/confirm",
     *     summary="Confirm a Payment Plan",
     *     tags={"Payment Plans"},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         description="ID of the payment plan to confirm",
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\Response(
     *         response=201,
     *         description="Payment Plan confirmed successfully",
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="Invalid request",
     *     ),
     *     @OA\Response(
     *         response=422,
     *         description="Validation error",
     *     )
     * )
     */

    public function confirm_payment($id)
    {
        try {
            $payment_plans = DB::transaction(function () use ($id) {
                $payment_plans =  $this->paymentPlansService->confirmarPayment($id);
                $this->bitacoraService->logActivity(ActivityTypes::PAYMENT_PLANS_CONFIRM, $payment_plans->sales->opportunity->customer, ['payment_plans' => $payment_plans]);
                $this->systemLogService->logActivity('pagos', 'Pago Confirmado', SeveritySystemLog::info->name, $payment_plans);
                if ($this->paymentPlansService->verifallpayment($payment_plans->sales)) {
                    $this->paymentPlansService->confirmSaleWithPayment($payment_plans->sales);
                    $this->systemLogService->logActivity('venta', 'Venta Confirmada', SeveritySystemLog::info->name, $payment_plans->sales);
                    $properties = $payment_plans->sales->property;
                    foreach ($properties as $property) {
                        $propertydata = $this->propertiesService->changeStatus($property->id, PropertyStatus::SALE->value); // Array access
                        $this->systemLogService->logActivity('propiedad', 'Propiedad Vendida', SeveritySystemLog::info->name, $propertydata);
                    }
                }
                return $payment_plans;
            });
            return ApiResponse::success(SuccessMessages::CREATE_SUCCESS, new PaymentPlansResource($payment_plans), [], 200);
        } catch (\Exception $e) {
            $this->systemLogService->logActivity('pagos', 'Confirmacion del pago fallida', SeveritySystemLog::error->name);
            return ApiResponse::error(ErrorMessages::BAD_REQUEST, $e->getMessage(), [], $e->getCode());
        }
    }

    /**
     * @OA\Patch(
     *     path="/api/sale/paymentPlans/{id}",
     *     summary="Update a Payment Plan",
     *     tags={"Payment Plans"},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         description="The ID of the payment plan to update",
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             type="object",
     *            @OA\Property(property="date", type="string", format="date", example="2024-10-05"),
     *            @OA\Property(
     *                 property="differData",
     *                 type="array",
     *                 description="Array of payment plan data to be updated",
     *                 @OA\Items(
     *                     @OA\Property(property="date", type="string", format="date", example="2024-10-05"),
     *                     @OA\Property(property="amount", type="number", format="float", example=5000),
     *                     @OA\Property(property="type", type="string", example="Installment")
     *                 )
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Payment plan updated successfully",
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="Invalid request",
     *     ),
     *     @OA\Response(
     *         response=422,
     *         description="Validation error",
     *     )
     * )
     */

    public function update_payment($id, UpdatePaymentPlansRequest $request)
    {
        try {
            $payment_plans = DB::transaction(function () use ($id, $request) {
                $isSplitting = $request->has('differData') && is_array($request->input('differData'));
                if ($isSplitting && !empty($request->input('differData'))) {
                    $payment_plans = $this->paymentPlansService->updatePayments($request->all(), $id);
                } else {
                    $data = [];
                    $data['date'] = $request->input('date');
                    $payment_plans = $this->paymentPlansService->updatePayment($data, $id);
                }
                $this->bitacoraService->logActivity(ActivityTypes::PAYMENT_PLANS_UPDATE, $payment_plans->sales->opportunity->customer,  ['payment_plans' => $payment_plans]);
                $this->systemLogService->logActivity('pagos', 'Pago Actualizado', SeveritySystemLog::info->name, $payment_plans);
                return $payment_plans;
            });
            return ApiResponse::success(SuccessMessages::CREATE_SUCCESS, new PaymentPlansResource($payment_plans), [], 200);
        } catch (\Exception $e) {
            $this->systemLogService->logActivity('pagos', 'Actualización del pago fallida', SeveritySystemLog::error->name);
            return ApiResponse::error(ErrorMessages::BAD_REQUEST, $e->getMessage(), [], $e->getCode());
        }
    }


    //      path="/api/sale/{id}/paymentPlans",
    public function update_sales_paymen_plans($id, UpdatePaymentPlansRequest $request)
    {
        try {

            $payment_plans = DB::transaction(function () use ($id, $request) {
                $isSplitting = $request->has('differData') && is_array($request->input('differData'));
                if ($isSplitting) {
                    $payment_plans = $this->paymentPlansService->updatePayments($request->all(), $id);
                } else {
                    $data = [];
                    $data['date'] = $request->input('date');
                    $payment_plans = $this->paymentPlansService->updatePayment($data, $id);
                }
                $this->bitacoraService->logActivity(ActivityTypes::PAYMENT_PLANS_UPDATE, $payment_plans->sales->opportunity->customer, ['payment_plans' => $payment_plans]);
                $this->systemLogService->logActivity('pagos', 'Pago Actualizado', SeveritySystemLog::info->name, $payment_plans);

                return $payment_plans;
            });
            return ApiResponse::success(SuccessMessages::CREATE_SUCCESS, new PaymentPlansResource($payment_plans), [], 200);
        } catch (\Exception $e) {
            $this->systemLogService->logActivity('pagos', 'Actualización del pago fallida', SeveritySystemLog::error->name);

            return ApiResponse::error(ErrorMessages::BAD_REQUEST, $e->getMessage(), [], $e->getCode());
        }
    }


}
