<?php

namespace Services;
require_once __DIR__ . '/../Services/Database.php';

use Services\Database;
use Exception;

class DonationService {

    public function insertDonation($donationData) {
        $conn = Database::getInstance()->getConnection();

        $sql = "INSERT INTO donation 
                (firstName, lastName, statusDonation, amount, email, phone, country, address, address2, zip, rfc, city, state, taxAddress, taxRegime, cfdiUsage, createdAt, satName)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        try {
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Error al preparar la consulta: " . $conn->error);
            }

            $statusDonation = 1;
            $createdAt = date('Y-m-d H:i:s');

            $stmt->bind_param(
                "ssidssssssssssssss",
                $donationData['firstName'],
                $donationData['lastName'],
                $statusDonation,
                $donationData['amount'],
                $donationData['email'],
                $donationData['phone'],
                $donationData['country'],
                $donationData['address'],
                $donationData['address2'],
                $donationData['zip'],
                $donationData['rfc'],
                $donationData['city'],
                $donationData['state'],
                $donationData['taxAddress'],
                $donationData['taxRegime'],
                $donationData['cfdiUsage'],
                $createdAt,
                $donationData['satName']
            );

            if (!$stmt->execute()) {
                throw new Exception("Error al ejecutar la consulta: " . $stmt->error);
            }

            error_log("Los datos se han guardado correctamente en la base de datos.");
        } catch (Exception $e) {
            error_log("Error al guardar los datos: " . $e->getMessage());
        } finally {
            if (isset($stmt)) {
                $stmt->close();
            }
        }
    }

    public function getLastDonation() {
        $conn = Database::getInstance()->getConnection();

        $sql = "SELECT * FROM donation WHERE statusDonation = 1 ORDER BY id DESC LIMIT 1";

        try {
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Error al preparar la consulta: " . $conn->error);
            }

            if (!$stmt->execute()) {
                throw new Exception("Error al ejecutar la consulta: " . $stmt->error);
            }

            $result = $stmt->get_result();
            $donation = $result->fetch_assoc();

            if ($donation) {
                error_log("Entra a búsqueda");

                if (empty($donation["cfdiUsage"]) || $donation["cfdiUsage"] === "G01 Gastos en general") {
                    $donation["cfdiUsage"] = "G03 Gastos en General";
                }

                return [
                    "id" => $donation["id"],
                    "email" => $donation["email"],
                    "rfc" => $donation["rfc"],
                    "amount" => $donation["amount"],
                    "cfdiUsage" => $donation["cfdiUsage"],
                    "taxRegime" => $donation["taxRegime"],
                    "address" => $donation["address"],
                    "address2" => $donation["address2"],
                    "zip" => $donation["zip"],
                    "city" => $donation["city"],
                    "state" => $donation["state"],
                    "satName" => $donation["satName"],
                    "firstName"=> $donation["firstName"],
                    "lastName"=> $donation["lastName"],
                    "phone"=> $donation["phone"],
                ];
            } else {
                error_log("No se encontraron resultados.");
                return null;
            }
        } catch (Exception $e) {
            error_log("Error al buscar la última donación: " . $e->getMessage());
            return null;
        } finally {
            if (isset($stmt)) {
                $stmt->close();
            }
        }
    }

    public function updateDonation($invoiceId, $donationId) {
        $conn = Database::getInstance()->getConnection();

        $sql = "UPDATE donation SET statusDonation = 2, invoiceId = ? WHERE id = ?";
        
        try {
            $stmt = $conn->prepare($sql);
            
            $stmt->bind_param("ii", $invoiceId, $donationId);
            
            $stmt->execute();

            error_log("La donación con ID $donationId ha sido actualizada correctamente con el invoiceId $invoiceId.");
        } catch (Exception $e) {
            error_log("Error al actualizar la donación: " . $e->getMessage());
        }
    }
    public function updateDonationCommission($donationId, $comisionStripe, $docRef)
    {
        try {
            $conn = Database::getInstance()->getConnection();

            $sql = "UPDATE donation SET statusDonation = 3, comisionStripe = ?, docRefStripe = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Error al preparar la consulta: " . $conn->error);
            }

            // Vincula los parámetros
            $stmt->bind_param("dsi", $comisionStripe, $docRef, $donationId);

            // Ejecuta la consulta
            if ($stmt->execute()) {
                error_log("Se ha actualizado la donación con la comisión de Stripe.");
            } else {
                throw new Exception("Error al ejecutar la consulta: " . $stmt->error);
            }

            $stmt->close();
        } catch (Exception $e) {
            error_log("Error al actualizar la comisión de la donación: " . $e->getMessage());
        }
    }
    public function updateDonationVendorBill($donationId, $vendorBillId)
    {
        try {
            $conn = Database::getInstance()->getConnection();

            $sql = "UPDATE donation SET statusDonation = 4, vendorBillId = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Error al preparar la consulta: " . $conn->error);
            }

            // Vincula los parámetros
            $stmt->bind_param("si", $vendorBillId, $donationId);

            // Ejecuta la consulta
            if ($stmt->execute()) {
                error_log("Se ha actualizado la donación con el ID de la factura del proveedor.");
            } else {
                throw new Exception("Error al ejecutar la consulta: " . $stmt->error);
            }

            $stmt->close();
        } catch (Exception $e) {
            error_log("Error al actualizar la factura del proveedor en la donación: " . $e->getMessage());
        }
    }
    public function updateDonationVendorPayment($donationId, $vendorPaymentId)
    {
        try {
            $conn = Database::getInstance()->getConnection();

            $sql = "UPDATE donation SET statusDonation = 5, vendorPaymentId = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Error al preparar la consulta: " . $conn->error);
            }

            // Vincula los parámetros
            $stmt->bind_param("si", $vendorPaymentId, $donationId);

            // Ejecuta la consulta
            if ($stmt->execute()) {
                error_log("Se ha actualizado la donación con el ID del pago al proveedor.");
            } else {
                throw new Exception("Error al ejecutar la consulta: " . $stmt->error);
            }

            $stmt->close();
        } catch (Exception $e) {
            error_log("Error al actualizar el pago al proveedor en la donación: " . $e->getMessage());
        }
    }
}

?>
