<?php

// Include the Stripe PHP library
require_once '../vendor/autoload.php';

// Assuming this is needed for other application logic
require_once "../models/Operations.php";

use Dotenv\Dotenv;
use Stripe\Stripe;
use Stripe\Subscription;
use Stripe\Charge;
use Stripe\Invoice;

$dotenv = Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

$stripeSecretKey = $_ENV['STRIPE_SECRET_KEY'];
$stripeWebhookSecret = $_ENV['STRIPE_WEBHOOK_SECRET'];

// https://localhost/evosyspos/

\Stripe\Stripe::setApiKey($stripeSecretKey);

// Retrieve the raw payload and signature from Stripe
$payload = file_get_contents('php://input'); // ONLY ONCE

// $payload = @file_get_contents('php://input');
$sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
$event = null;

try {
    // Verify the webhook signature
    $event = \Stripe\Webhook::constructEvent($payload, $sigHeader, $stripeWebhookSecret);
    // file_put_contents(__DIR__ . '/stripe_debug.log', "Stripe event: " . $event . "\n", FILE_APPEND);
} catch (\UnexpectedValueException $e) {
    // Invalid payload
    http_response_code(400);
    // file_put_contents(__DIR__ . '/stripe_debug.log', "Error parsing payload: " . $e->getMessage() . "\n", FILE_APPEND);
    exit();
} catch (\Stripe\Exception\SignatureVerificationException $e) {
    // Invalid signature
    http_response_code(400);
    // file_put_contents(__DIR__ . '/stripe_debug.log', "Error verifying webhook signature: " . $e->getMessage() . "\n", FILE_APPEND);
    exit();
}

// ✅ Access the object safely
$stripe_response = $event->data->object ?? null;
$eventType = $event->type ?? '';

// 📧 Function to send email using Resend API
function sendEmailSubscription($send_to, $subject, $htmlBody = "", $reply_to = "", $cc = [], $bcc = [], $fileAttachment = "")
{
    $resend = Resend::client($_ENV['RESEND_ACCESS_KEY']);

    try {
        // Prepare the basic email data
        $emailData = [
            'from' => "no-reply@{$_ENV['PRODUCT_DOMAIN']}", // Get domain from environment variables
            'to' => $send_to, // Array of recipients
            'reply_to' => $reply_to, // Reply-to address
            'subject' => $subject, // Subject of the email
            'html' => $htmlBody, // HTML body content
        ];

        // Add CC if provided
        if (!empty($cc)) {
            $emailData['cc'] = $cc;  // CC recipients
        }

        // Add BCC if provided
        if (!empty($bcc)) {
            $emailData['bcc'] = $bcc;  // BCC recipients
        }

        // Send email via Resend API
        $result = $resend->emails->send($emailData);

        $response = array("emailId" => $result, "status" => "success", "title" => "Success", "message" => "Email sent successfully");
        return $response;  // Return result if successful

    } catch (\Exception $e) {
        // Handle exceptions and errors
        $response = array("status" => "error", "title" => "Error", "message" => "Email could not be sent", "error" => "Error: " . $e->getMessage() . "");
        return $response;
    }
}

// 🎯 Handle your Stripe events
switch ($eventType) {

    case 'checkout.session.completed':
        // Checkout Session Completed: El cliente ha completado su pago en una página de pago Stripe Checkout, que incluye todo el flujo del proceso de pago.

        // price_1RT4xxKaWzEqPgeUIJCb5E96
        // price_1Sjxsz4DHWfU768ZmZZSh52U

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Checkout Session Completed: " . $stripe_response . "\n", FILE_APPEND);

        $app_source = $stripe_response->metadata->app_source ?? null;

        if ($app_source === 'evosyspos') {

            // $session_id = $stripe_response->id;
            // $session_subscription_id = $stripe_response->subscription;
            // $subscriptionInfo = \Stripe\Subscription::retrieve($session_subscription_id);

            $session_customer_id = $stripe_response->customer;
            $session_enterprise_id = $stripe_response->metadata->enterprise_id ?? null;
            $session_payment_status = $stripe_response->payment_status;

            $sessionMode = $stripe_response->mode;

            \Stripe\Customer::update($session_customer_id, [
                'metadata' => [
                    'enterprise_id' => $session_enterprise_id,
                    'app_source'    => $app_source,
                ],
            ]);

            // --- 1. Check for Successful One-Time Payment (mode: payment) ---
            if ($sessionMode === 'payment' && $session_payment_status === 'paid') {
                // 🎉 Success: One-time payment received.
                // (e.g., update DB, send confirmation email, grant access to digital product)
            }
            // --- 2. Check for Successful Subscription Activation (mode: subscription) ---
            elseif ($sessionMode === 'subscription' && ($session_payment_status === 'paid' || $session_payment_status === 'no_payment_required')) {

                // 🎉 Success: Subscription activated.
            }
        }

        break;


    case 'invoice.created':

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Invoice Created: " . $stripe_response . "\n", FILE_APPEND);

        $invoiceId = $stripe_response->id;
        $amountDue = $stripe_response->amount_due / 100; // Convert cents to dollars
        $amountPaid = $stripe_response->amount_paid / 100; // Convert cents to dollars
        $amountRemaining = $stripe_response->amount_remaining / 100; // Convert cents to dollars
        $customerId = $stripe_response->customer;
        $customerAccountId = $stripe_response->customer_account ?? null;
        $customerEmail = $stripe_response->customer_email ?? null;
        $customerFullName = $stripe_response->customer_name ?? null;
        $customerPhone = $stripe_response->customer_phone ?? null;
        $invCurrency = $stripe_response->currency ?? null;
        $invoiceUrl = $stripe_response->hosted_invoice_url ?? null;
        $invDate        = date('Y-m-d H:i:s', $stripe_response->created) ?? null;
        $invPeriodStart = date('Y-m-d', $stripe_response->period_start) ?? null;
        $invPeriodEnd   = date('Y-m-d', $stripe_response->period_end) ?? null;
        $invoiceStatus = $stripe_response->status;
        $subscriptionId = $stripe_response->parent->subscription_details->subscription;
        $app_source = $stripe_response->parent->subscription_details->metadata->app_source ?? $stripe_response->metadata->app_source;
        $subs_enterprise_id = $stripe_response->parent->subscription_details->metadata->enterprise_id ?? $stripe_response->metadata->enterprise_id;

        if ($app_source === 'evosyspos') {
            // Save invoice details to the database
            $sqlSaveInvoice = "INSERT INTO tb_stripe_invoices (inv_stripe_invoice_id, inv_subscription_id, inv_customer_id, inv_customer_account_id, inv_enterprise_id, inv_customer_email, inv_customer_name, inv_customer_phone, inv_amount_due, inv_amount_paid, inv_amount_remaining, inv_currency, inv_hosted_url, inv_date, inv_period_start, inv_period_end, inv_status) VALUES ('{$invoiceId}', '{$subscriptionId}', '{$customerId}', '{$customerAccountId}', '{$subs_enterprise_id}', '{$customerEmail}', '{$customerFullName}', '{$customerPhone}', '{$amountDue}', '{$amountPaid}', '{$amountRemaining}', '{$invCurrency}', '{$invoiceUrl}', '{$invDate}', '{$invPeriodStart}', '{$invPeriodEnd}', '{$invoiceStatus}');";
            executeQueryPDOApi($sqlSaveInvoice, "Updated", "INVOICES");
        }

        break;


    case 'invoice.finalized':

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Invoice Finalized: " . $stripe_response . "\n", FILE_APPEND);

        $invoiceId = $stripe_response->id;
        $amountDue = $stripe_response->amount_due / 100; // Convert cents to dollars
        $amountPaid = $stripe_response->amount_paid / 100; // Convert cents to dollars
        $amountRemaining = $stripe_response->amount_remaining / 100; // Convert cents to dollars
        $invCurrency = $stripe_response->currency;
        $invoiceUrl = $stripe_response->hosted_invoice_url;
        $invoiceStatus = $stripe_response->status;
        $app_source = $stripe_response->parent->subscription_details->metadata->app_source ?? $stripe_response->metadata->app_source;

        if ($app_source === 'evosyspos') {

            $sqlUpdateInvoice = "UPDATE tb_stripe_invoices SET 
            inv_amount_due = '{$amountDue}',
            inv_amount_paid = '{$amountPaid}',
            inv_amount_remaining = '{$amountRemaining}',
            inv_currency = '{$invCurrency}',
            inv_hosted_url = '{$invoiceUrl}',
            inv_status = '{$invoiceStatus}'
            WHERE inv_stripe_invoice_id = '{$invoiceId}';";
            executeQueryPDOApi($sqlUpdateInvoice, "Updated", "INVOICES");
        }

        break;


    case 'invoice.updated':

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Invoice Updated: " . $stripe_response . "\n", FILE_APPEND);

        $invoiceId = $stripe_response->id;
        $amountDue = $stripe_response->amount_due / 100; // Convert cents to dollars
        $amountPaid = $stripe_response->amount_paid / 100; // Convert cents to dollars
        $amountRemaining = $stripe_response->amount_remaining / 100; // Convert cents to dollars
        $customerId = $stripe_response->customer;
        $customerAccountId = $stripe_response->customer_account ?? null;
        $customerEmail = $stripe_response->customer_email ?? null;
        $customerFullName = $stripe_response->customer_name ?? null;
        $customerPhone = $stripe_response->customer_phone ?? null;
        $invCurrency = $stripe_response->currency ?? null;
        $invoiceUrl = $stripe_response->hosted_invoice_url ?? null;
        $invDate        = date('Y-m-d H:i:s', $stripe_response->created) ?? null;
        $invPeriodStart = date('Y-m-d', $stripe_response->period_start) ?? null;
        $invPeriodEnd   = date('Y-m-d', $stripe_response->period_end) ?? null;
        $invoiceStatus = $stripe_response->status;
        $subscriptionId = $stripe_response->parent->subscription_details->subscription;
        $app_source = $stripe_response->parent->subscription_details->metadata->app_source ?? $stripe_response->metadata->app_source;
        $subs_enterprise_id = $stripe_response->parent->subscription_details->metadata->enterprise_id ?? $stripe_response->metadata->enterprise_id;

        if ($app_source === 'evosyspos') {

            // check if this subscription already exists in DB to avoid duplicates
            $sqlCheck = "SELECT COUNT(*) as count FROM tb_stripe_invoices WHERE inv_stripe_invoice_id = '$invoiceId';";
            $resultCheck = executePDOFetchAllAPI($sqlCheck);

            // Check if subscription already exists in the database
            if ($resultCheck['status'] == 'success') {
                // Invoice already exists in the database, update it.

                $sqlUpdateInvoice = "UPDATE tb_stripe_invoices SET 
                inv_amount_due = '{$amountDue}',
                inv_amount_paid = '{$amountPaid}',
                inv_amount_remaining = '{$amountRemaining}',
                inv_currency = '{$invCurrency}',
                inv_hosted_url = '{$invoiceUrl}',
                inv_status = '{$invoiceStatus}'
                WHERE inv_stripe_invoice_id = '{$invoiceId}';";
                executeQueryPDOApi($sqlUpdateInvoice, "Updated", "INVOICES");
            } else {
                // Save invoice details to the database
                $sqlSaveInvoice = "INSERT INTO tb_stripe_invoices (inv_stripe_invoice_id, inv_subscription_id, inv_customer_id, inv_customer_account_id, inv_enterprise_id, inv_customer_email, inv_customer_name, inv_customer_phone, inv_amount_due, inv_amount_paid, inv_amount_remaining, inv_currency, inv_hosted_url, inv_date, inv_period_start, inv_period_end, inv_status) VALUES ('{$invoiceId}', '{$subscriptionId}', '{$customerId}', '{$customerAccountId}', '{$subs_enterprise_id}', '{$customerEmail}', '{$customerFullName}', '{$customerPhone}', '{$amountDue}', '{$amountPaid}', '{$amountRemaining}', '{$invCurrency}', '{$invoiceUrl}', '{$invDate}', '{$invPeriodStart}', '{$invPeriodEnd}', '{$invoiceStatus}');";
                executeQueryPDOApi($sqlSaveInvoice, "Saved", "INVOICES");
            }
        }

        break;


    case 'invoice.payment_succeeded':

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Invoice Payment Succeeded: " . $stripe_response . "\n", FILE_APPEND);

        $invoiceId = $stripe_response->id;
        $amountDue = $stripe_response->amount_due / 100; // Convert cents to dollars
        $amountPaid = $stripe_response->amount_paid / 100; // Convert cents to dollars
        $amountRemaining = $stripe_response->amount_remaining / 100; // Convert cents to dollars
        $customerEmail = $stripe_response->customer_email;
        $customerFullName = $stripe_response->customer_name;
        $invCurrency = $stripe_response->currency;
        $invoiceUrl = $stripe_response->hosted_invoice_url;
        $invoiceStatus = $stripe_response->status;
        $subscriptionId = $stripe_response->parent->subscription_details->subscription;
        $app_source = $stripe_response->parent->subscription_details->metadata->app_source ?? $stripe_response->metadata->app_source;
        $subs_enterprise_id = $stripe_response->parent->subscription_details->metadata->enterprise_id ?? $stripe_response->metadata->enterprise_id;

        $subscriptionInfo = \Stripe\Subscription::retrieve($subscriptionId);
        $subscription_status = $subscriptionInfo->status ?? null;

        if ($app_source === 'evosyspos') {

            // Update invoice details in the database here
            $sqlUpdateInvoice = "UPDATE tb_stripe_invoices SET 
            inv_amount_due = '{$amountDue}',
            inv_amount_paid = '{$amountPaid}',
            inv_amount_remaining = '{$amountRemaining}',
            inv_currency = '{$invCurrency}',
            inv_hosted_url = '{$invoiceUrl}',
            inv_status = '{$invoiceStatus}'
            WHERE inv_stripe_invoice_id = '{$invoiceId}';";
            executeQueryPDOApi($sqlUpdateInvoice, "Updated", "INVOICES");

            // Update subscription status in your database here
            $sqlUpdateSubscription = "UPDATE tb_stripe_subscriptions SET subscription_status = '{$subscription_status}' WHERE subs_subscription_id = '{$subscriptionId}';";
            executeQueryPDOApi($sqlUpdateSubscription, "Updated", "SUBSCRIPTIONS");

            // Update enterprise subscription status in your database here
            if ($subs_enterprise_id !== null) {
                $sql = "UPDATE tb_enterprises SET ent_stripe_subscription_status = '{$subscription_status}' WHERE ent_id='{$subs_enterprise_id}';";
                executeQueryPDOApi($sql, "Updated", "ENTERPRISES");
            }

            if (!empty($customerEmail)) {

                $subject = "Payment Successful: Invoice for Your EVOSYS POS Subscription";
                $htmlBody = "<p>Dear {$customerFullName},</p>
                <p>We are pleased to inform you that your payment of \${$amountPaid} for your subscription (ID: {$subscriptionId}) has been successfully processed.</p>
                <p>You can download your invoice and receipt by clicking the link below:</p>
                <p><a href='{$invoiceUrl}' target='_blank'>View Invoice</a></p>
                <p>Thank you for being a valued customer. If you have any questions or need further assistance, please do not hesitate to contact our support team.</p>
                <p>Best regards, <br>ITECEVO LLC</p>
                <p>Please reply to: support@{$_ENV['COMPANY_DOMAIN']}</p>";

                $reply_to = "support@{$_ENV['COMPANY_DOMAIN']}"; // Get domain from environment variables
                // Send a confirmation email to the user.
                $response = sendEmailSubscription($customerEmail, $subject, $htmlBody, $reply_to);

                // file_put_contents(__DIR__ . '/stripe_debug.log', "RESEND EMAIL: " . json_encode($response) . "\n", FILE_APPEND);
            }
        }

        // Update DB
        break;


    case 'invoice.payment_failed':

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Invoice Payment Failed: " . $stripe_response . "\n", FILE_APPEND);

        // Customers’ cards can fail temporarily (expired, insufficient funds, etc.).
        // Payment failed (first or retry)
        // ⚠️ Notify user, don’t revoke access yet

        $invoiceId = $stripe_response->id;
        $subscriptionId = $stripe_response->parent->subscription_details->subscription;
        $invoiceUrl = $stripe_response->hosted_invoice_url;
        $customerEmail = $stripe_response->customer_email;
        $invoiceStatus = $stripe_response->status;

        $subscriptionInfo = \Stripe\Subscription::retrieve($subscriptionId);
        $app_source = $subscriptionInfo->metadata->app_source ?? null;

        if ($app_source === 'evosyspos') {

            // Update enterprise subscription status in your database here
            $sql = "UPDATE tb_stripe_invoices SET inv_status = '{$invoiceStatus}' WHERE inv_stripe_invoice_id='{$invoiceId}';";
            executeQueryPDOApi($sql, "Updated", "INVOICES");

            if (!empty($customerEmail)) {

                $subject = "Action Required: Payment Issue with Your EVOSYS POS Subscription";
                $htmlBody = "<p>Dear Customer,</p>
                    <p>We wanted to inform you that there was an issue processing the payment for your subscription (ID: {$subscriptionId}). Please update your payment information to avoid interruption of your service.</p>
                    <p>You can pay your invoice by clicking the link below:</p>
                    <p><a href='{$invoiceUrl}' target='_blank'>Pay Invoice</a></p>
                    <p>You can manage your subscription and update your payment details by visiting the following link:</p>
                    <p>https://billing.stripe.com/p/login/eVqcN6ec94uM1Kr5iRaVa00?prefilled_email={$customerEmail}</p>
                    <p>If you have any questions or need assistance, feel free to contact our support team.</p>
                    <p>Thank you for being a valued customer.</p>
                    <p>Best regards, <br>ITECEVO LLC</p>
                    <p>Please reply to: support@{$_ENV['COMPANY_DOMAIN']}</p>";

                $reply_to = "support@{$_ENV['COMPANY_DOMAIN']}"; // Get domain from environment variables
                // Send a confirmation email to the user.
                $response = sendEmailSubscription($customerEmail, $subject, $htmlBody, $reply_to);
            }
        }

        break;


    case 'customer.subscription.created':

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Customer Subscription Created: " . $stripe_response . "\n", FILE_APPEND);

        $app_source = $stripe_response->metadata->app_source ?? null;

        $subs_subscription_id = $stripe_response->id;
        $subs_price_id = $stripe_response->plan->id ?? null;
        $subs_customer_id = $stripe_response->customer;
        $subs_customer_account_id = $stripe_response->customer_account ?? null;
        $subs_enterprise_id = $stripe_response->metadata->enterprise_id ?? null;
        $subs_quantity = $stripe_response->quantity ?? 1;
        $subs_amount_unit = $stripe_response->plan->amount ? ($stripe_response->plan->amount / 100) : 0;
        $subs_currency = $stripe_response->plan->currency ?? null;
        $subs_interval = $stripe_response->plan->interval ?? 1;
        $subs_interval_count = $stripe_response->plan->interval_count ?? 1;
        $subscription_status = $stripe_response->status;
        $subs_created = date('Y-m-d H:i:s', $stripe_response->created) ?? null;
        $subs_current_period_start = date('Y-m-d H:i:s', $stripe_response->current_period_start) ?? null;
        $subs_current_period_end = date('Y-m-d H:i:s', $stripe_response->current_period_end) ?? null;
        $subs_trial_end = date('Y-m-d H:i:s', $stripe_response->trial_end) ?? null;

        if ($app_source === 'evosyspos') {

            // Save subscription details to the database
            $sql = "INSERT INTO tb_stripe_subscriptions (subs_subscription_id,subs_price_id,subs_customer_id,subs_customer_account_id,subs_enterprise_id,subs_quantity,subs_amount_unit,subs_currency,subs_interval,subs_interval_count,subscription_status,subs_created,subs_current_period_start,subs_current_period_end,subs_trial_end) VALUES ('$subs_subscription_id','$subs_price_id','$subs_customer_id','$subs_customer_account_id','$subs_enterprise_id','$subs_quantity','$subs_amount_unit','$subs_currency','$subs_interval','$subs_interval_count','$subscription_status','$subs_created','$subs_current_period_start','$subs_current_period_end','$subs_trial_end');";
            // exit($sql);

            executeQueryPDOApi($sql, "Saved", "SUBSCRIPTIONS");
        }

        break;



    case 'customer.subscription.updated':

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Customer Subscription Update: " . $stripe_response . "\n", FILE_APPEND);

        // Subscription status changed
        // 👀 Check if status became unpaid, canceled, or incomplete_expired → revoke access
        $app_source = $stripe_response->metadata->app_source ?? null;

        $subs_subscription_id = $stripe_response->id;
        $subs_price_id = $stripe_response->plan->id ?? null;
        $subs_customer_id = $stripe_response->customer;
        $subs_customer_account_id = $stripe_response->customer_account ?? null;
        $subs_enterprise_id = $stripe_response->metadata->enterprise_id ?? null;
        $subs_quantity = $stripe_response->quantity ?? 1;
        $subs_amount_unit = $stripe_response->plan->amount ? ($stripe_response->plan->amount / 100) : 0;
        $subs_currency = $stripe_response->plan->currency ?? null;
        $subs_interval = $stripe_response->plan->interval ?? 1;
        $subs_interval_count = $stripe_response->plan->interval_count ?? 1;
        $subscription_status = $stripe_response->status;
        $subs_created = date('Y-m-d H:i:s', $stripe_response->created) ?? null;
        $subs_current_period_start = date('Y-m-d H:i:s', $stripe_response->current_period_start) ?? null;
        $subs_current_period_end = date('Y-m-d H:i:s', $stripe_response->current_period_end) ?? null;
        $subs_trial_end = date('Y-m-d H:i:s', $stripe_response->trial_end) ?? null;

        if ($app_source === 'evosyspos') {

            $sqlGetSubscription = "SELECT subs_subscription_id FROM tb_stripe_subscriptions WHERE subs_subscription_id = '{$subs_subscription_id}';";
            $resSubscriptionInfo = executePDOFetchOneAPI($sqlGetSubscription);

            // Confirm subscription exists before updating status and notifying user
            if ($resSubscriptionInfo['status'] == 'success') {

                // Update subscription status in your database here
                $sqlUpdateSubscription = "UPDATE tb_stripe_subscriptions SET subs_price_id = '{$subs_price_id}', subs_customer_id = '{$subs_customer_id}', subs_customer_account_id = '{$subs_customer_account_id}', subs_enterprise_id = '{$subs_enterprise_id}', subs_quantity = '{$subs_quantity}', subs_amount_unit = '{$subs_amount_unit}', subs_currency = '{$subs_currency}', subs_interval = '{$subs_interval}', subs_interval_count = '{$subs_interval_count}', subscription_status = '{$subscription_status}', subs_current_period_end = '{$subs_current_period_end}', subs_trial_end = '{$subs_trial_end}' WHERE subs_subscription_id = '{$subs_subscription_id}';";

                executeQueryPDOApi($sqlUpdateSubscription, "Updated", "SUBSCRIPTIONS");

                if (!empty($subs_enterprise_id)) {

                    // Update enterprise subscription status in your database here
                    $sql = "UPDATE tb_enterprises SET ent_stripe_customer_id = '{$subs_customer_id}', ent_stripe_subscription_id = '{$subs_subscription_id}', ent_stripe_subscription_status = '{$subscription_status}' WHERE ent_id='{$subs_enterprise_id}';";
                    executeQueryPDOApi($sql, "Updated", "ENTERPRISES");
                }

                $sqlGetCustomer = "SELECT customer_email FROM tb_stripe_customers WHERE customer_id = '{$subs_customer_id}';";
                $resCustomerInfo = executePDOFetchOneAPI($sqlGetCustomer);

                $customer_email = $resCustomerInfo['data']['customer_email'] ?? "";

                if (!empty($customer_email)) {

                    $subject = "";
                    $htmlBody = "";

                    // Prepare email based on status
                    if ($subscription_status == 'past_due' || $subscription_status == 'incomplete') {
                        // Payment failed but retries ongoing. Keep access, send reminders.
                        $subject = "Action Required: Payment Issue with Your EVOSYS POS Subscription";
                        $htmlBody = "<p>Dear Customer,</p>
                        <p>We wanted to inform you that there was an issue processing the payment for your subscription (ID: {$subs_subscription_id}). Please update your payment information to avoid interruption of your service.</p>
                        <p>You can manage your subscription and update your payment details by visiting the following link:</p>
                        <p>https://app.evosyspos.com/billing</p>
                        <p>If you have any questions or need assistance, feel free to contact our support team.</p>
                        <p>Thank you for being a valued customer.</p>
                        <p>Best regards, <br>ITECEVO LLC</p>
                        <p>Please reply to: support@{$_ENV['COMPANY_DOMAIN']}</p>";
                    } elseif ($subscription_status == 'unpaid') {
                        // All retries failed, Stripe stopped trying.
                        $subject = "EVOSYS POS Subscription Unpaid: Access Revoked";
                        $htmlBody = "<p>Dear Customer,</p>
                        <p>We regret to inform you that your subscription (ID: {$subs_subscription_id}) has been marked as unpaid after multiple unsuccessful payment attempts. As a result, your access to our services has been revoked.</p>
                        <p>If you believe this is a mistake or if you would like to reactivate your subscription, please update your payment information or contact our support team for assistance.</p>
                        <p>You can manage your subscription by visiting the following link:</p>
                        <p>https://app.evosyspos.com/billing</p>
                        <p>Thank you for your understanding.</p>
                        <p>Best regards, <br>ITECEVO LLC</p>
                        <p>Please reply to: support@{$_ENV['COMPANY_DOMAIN']}</p>";
                    } elseif ($subscription_status == 'canceled' || $subscription_status == 'incomplete_expired') {
                        // Log unexpected status.
                        $subject = "EVOSYS POS Subscription Canceled or Expired: Access Revoked";
                        $htmlBody = "<p>Dear Customer,</p>
                        <p>We wanted to inform you that your subscription (ID: {$subs_subscription_id}) has been canceled or has expired. As a result, your access to our services has been revoked.</p>
                        <p>If you would like to reactivate your subscription or if you have any questions, please contact our support team for assistance.</p>
                        <p>You can manage your subscription by visiting the following link:</p>
                        <p>https://app.evosyspos.com/billing</p>
                        <p>Thank you for your understanding.</p>
                        <p>Best regards, <br>ITECEVO LLC</p>
                        <p>Please reply to: support@{$_ENV['COMPANY_DOMAIN']}</p>";
                    } elseif ($subscription_status == 'trialing') {
                        // Log unexpected status.
                        $subject = "EVOSYS POS Subscription is now in Trialing status";
                        $htmlBody = "<p>Dear Customer,</p>
                        <p>Your subscription (ID: {$subs_subscription_id}) is now in a trialing status. Enjoy your trial period!</p>
                        <p>If you have any questions or need assistance, feel free to contact our support team.</p>
                        <p>Thank you for being a valued customer.</p>
                        <p>Best regards, <br>ITECEVO LLC</p>
                        <p>Please reply to: support@{$_ENV['COMPANY_DOMAIN']}</p>";
                    }

                    $reply_to = "support@{$_ENV['COMPANY_DOMAIN']}"; // Get domain from environment variables
                    // Send a confirmation email to the user.
                    $response = sendEmailSubscription($customer_email, $subject, $htmlBody, $reply_to);
                }
            } else {

                // Save subscription details to the database
                $sql = "INSERT INTO tb_stripe_subscriptions (subs_subscription_id,subs_price_id,subs_customer_id,subs_customer_account_id,subs_enterprise_id,subs_quantity,subs_amount_unit,subs_currency,subs_interval,subs_interval_count,subscription_status,subs_created,subs_current_period_start,subs_current_period_end,subs_trial_end) VALUES ('$subs_subscription_id','$subs_price_id','$subs_customer_id','$subs_customer_account_id','$subs_enterprise_id','$subs_quantity','$subs_amount_unit','$subs_currency','$subs_interval','$subs_interval_count','$subscription_status','$subs_created','$subs_current_period_start','$subs_current_period_end','$subs_trial_end');";
                // exit($sql);

                executeQueryPDOApi($sql, "Saved", "SUBSCRIPTIONS");
            }
        }

        break;


    case 'customer.subscription.deleted':

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Customer Subscription Deleted: " . $stripe_response . "\n", FILE_APPEND);

        // Subscription canceled (manual or automatic)
        // 🔒 Revoke access inmediately

        $subscriptionId = $stripe_response->id;
        $subs_customer_id = $stripe_response->customer;
        $subscription_status = $stripe_response->status;
        $subsCanceledAt = date('Y-m-d H:i:s', $stripe_response->canceled_at) ?? null;

        $app_source = $stripe_response->metadata->app_source ?? null;
        $subs_enterprise_id = $stripe_response->metadata->enterprise_id ?? null;

        if ($app_source === 'evosyspos') {

            // Update subscription status in your database here
            $sqlUpdateSubscription = "UPDATE tb_stripe_subscriptions SET subscription_status = '{$subscription_status}', subs_canceled_at = '{$subsCanceledAt}' WHERE subs_subscription_id = '{$subscriptionId}';";
            executeQueryPDOApi($sqlUpdateSubscription, "Updated", "SUBSCRIPTIONS");

            // Update enterprise subscription status in your database here
            if (!empty($subs_enterprise_id)) {
                $sql = "UPDATE tb_enterprises SET ent_stripe_subscription_status = '{$subscription_status}' WHERE ent_id='{$subs_enterprise_id}';";
                executeQueryPDOApi($sql, "Updated", "ENTERPRISES");
            }

            $sqlGetCustomer = "SELECT customer_email FROM tb_stripe_customers WHERE customer_id = '{$subs_customer_id}';";
            $resCustomerInfo = executePDOFetchOneAPI($sqlGetCustomer);

            if ($resCustomerInfo['status'] == 'success') {
                // Handle error if subscription not found

                $customer_email = $resCustomerInfo['data']['customer_email'] ?? "";

                if (!empty($customer_email)) {

                    $subject = "EVOSYS POS Subscription Canceled: Access Revoked";
                    $htmlBody = "<p>Dear Customer,</p>
                    <p>Your subscription (ID: {$subscriptionId}) has been successfully cancelled. We're sorry to see you go! If you have any feedback or need assistance, please don't hesitate to contact our support team.</p>
                    <p>If you would like to reactivate your subscription or if you have any questions, please contact our support team for assistance.</p>
                    <p>You can manage your subscription by visiting the following link:</p>
                    <p>https://app.evosyspos.com/billing</p>
                    <p>Thank you for your understanding.</p>
                    <p>Best regards, <br>ITECEVO LLC</p>
                    <p>Please reply to: support@{$_ENV['COMPANY_DOMAIN']}</p>";

                    $reply_to = "support@{$_ENV['COMPANY_DOMAIN']}"; // Get domain from environment variables
                    // Send a confirmation email to the user.
                    $response = sendEmailSubscription($customer_email, $subject, $htmlBody, $reply_to);
                }
            }
        }
        break;


    case 'customer.updated':
        // Customer Updated: El pago ha sido procesado exitosamente a través de un flujo más avanzado de autorización y autenticación (incluyendo 3D Secure).

        // Log the event for debugging
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Customer Updated: " . $stripe_response . "\n", FILE_APPEND);

        $app_source = $stripe_response->metadata->app_source ?? null;

        if ($app_source === 'evosyspos') {

            $customer_id = $stripe_response->id;
            $customer_account_id = $stripe_response->customer_account ?? null;
            $customer_enterprise_id = $stripe_response->metadata->enterprise_id ?? null;
            $customer_email = $stripe_response->email ?? null;
            $customer_name = $stripe_response->name ?? null;
            $customer_phone = $stripe_response->phone ?? null;
            $customer_city = $stripe_response->address->city ?? null;
            $customer_country = $stripe_response->address->country ?? null;
            $customer_line1 = $stripe_response->address->line1 ?? null;
            $customer_line2 = $stripe_response->address->line2 ?? null;
            $customer_postal_code = $stripe_response->address->postal_code ?? null;
            $customer_state = $stripe_response->address->state ?? null;
            $customer_language = $stripe_response->preferred_locales[0] ?? null;
            $customer_app_source = $stripe_response->metadata->app_source ?? null;
            $customer_balance = $stripe_response->balance ?? 0;
            $customer_created_at = date('Y-m-d H:i:s', $stripe_response->created) ?? null;

            // check if this customer already exists in DB to avoid duplicates
            $sqlCheck = "SELECT COUNT(*) as count FROM tb_stripe_customers WHERE customer_id = '$customer_id';";
            $resultCheck = executePDOFetchAllAPI($sqlCheck);

            // Check if customer already exists in the database
            if ($resultCheck['status'] == 'success') {

                // Update customer details in the database
                $sql = "UPDATE tb_stripe_customers SET customer_account_id = '$customer_account_id', customer_enterprise_id = '$customer_enterprise_id', customer_email = '$customer_email', customer_name = '$customer_name', customer_phone = '$customer_phone', customer_city = '$customer_city', customer_country = '$customer_country', customer_line1 = '$customer_line1', customer_line2 = '$customer_line2', customer_postal_code = '$customer_postal_code', customer_state = '$customer_state', customer_language = '$customer_language', customer_app_source = '$customer_app_source', customer_balance = '$customer_balance' WHERE customer_id = '$customer_id';";
                executeQueryPDOApi($sql, "Updated", "CUSTOMERS");
            } else {

                // Save customer details to the database
                $sql = "INSERT INTO tb_stripe_customers (customer_id, customer_account_id, customer_enterprise_id, customer_email, customer_name, customer_phone, customer_city, customer_country, customer_line1, customer_line2, customer_postal_code, customer_state, customer_language, customer_app_source, customer_balance, customer_created_at) VALUES ('$customer_id', '$customer_account_id', '$customer_enterprise_id', '$customer_email', '$customer_name', '$customer_phone', '$customer_city', '$customer_country', '$customer_line1', '$customer_line2', '$customer_postal_code', '$customer_state', '$customer_language', '$customer_app_source', '$customer_balance', '$customer_created_at');";
                executeQueryPDOApi($sql, "Saved", "CUSTOMERS");
            }

            // Update enterprise subscription status in your database here
            $sql = "UPDATE tb_enterprises SET 
            ent_stripe_customer_id = '{$customer_id}',
            ent_email = '{$customer_email}'
            WHERE ent_id='{$customer_enterprise_id}';";
            executeQueryPDOApi($sql, "Updated", "ENTERPRISES");
        }

        break;


    case 'payment_intent.succeeded':
        // Payment Intent Succeeded: El pago ha sido procesado exitosamente a través de un flujo más avanzado de autorización y autenticación (incluyendo 3D Secure).

        // Log the event for debugging
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Payment Intent Succeeded: " . $stripe_response . "\n", FILE_APPEND);

        break;


    case 'product.deleted':

        // Log the event
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Product Deleted: " . $stripe_response . "\n", FILE_APPEND);

        // Update DB
        $sql = "DELETE FROM tb_stripe_plans WHERE plan_product_id='{$stripe_response->id}';";
        executeQueryPDO($sql);
        break;


    // ... handle other event types
    default:
        // Log the event
        // echo 'Received unknown event type ' . $eventType;
        // file_put_contents(__DIR__ . '/stripe_debug.log', "Unknown Event Type: " . $eventType . "\n", FILE_APPEND);
}

// stripe login
// stripe listen --forward-to https://evosyspos.test/stripe/stripe-webhook.php
// stripe listen --forward-to http://localhost/evosyspos/stripe/stripe-webhook.php