<?php
    include_once 'inc/database.php';
    include_once 'requestFunctions.php';
    require_once __DIR__ . '/vendor/autoload.php';
    
    \Stripe\Stripe::setApiKey($stripe['secret_key']);
    
    // Function to write logs to a subscription-specific file
    function writeLog($subscriptionId, $message, $data = []) {
        // Use a default log file if subscription ID is missing
        $logFile = $subscriptionId ? "stripe_logs/stripe_log_{$subscriptionId}.txt" : "stripe_logs/stripe_log_default.txt";
    
        $logMessage = "[" . date("Y-m-d H:i:s") . "] " . $message . "\n";
        if (!empty($data)) {
            $logMessage .= "Details: " . json_encode($data, JSON_PRETTY_PRINT) . "\n";
        }
    
        file_put_contents($logFile, $logMessage, FILE_APPEND);
    }

    
    $payload = @file_get_contents('php://input');
    $event = null; 
    try {
        $event = \Stripe\Event::constructFrom(
            json_decode($payload, true)
        );
    } catch(\UnexpectedValueException $e) {
        exit();
    }
    $app_subscription_amount = DEFAULT_PRICE;
    $paymentIntent = $event->data->object;
    $customer_id = $paymentIntent->customer;
    $stripe_subscription_id = $paymentIntent->id;
    
    $store_id = $db->getSingleColumn( "subscription", "store_id", array( "stripe_customer_id" => $customer_id ));
    if($customer_id){
        writeLog($stripe_subscription_id, "Customer ID detected", ["customer_id" => $customer_id, "event_type" => $event->type]);
        if($paymentIntent->type == "charge.succeeded"){
            
            writeLog($stripe_subscription_id, "payment Successful - Activating Subscription and charge.succeeded if condition run", [
                "amount_paid" => $paymentIntent->amount / 100,
                "currency" => $paymentIntent->currency,
                "status" => "paid"
            ]);
            
            
            switch ($paymentIntent->paid) {
                case '1':{
                    
                    writeLog($stripe_subscription_id, "payment Successful - Activating Subscription Case 1 Run status is active in db", [
                        "amount_paid" => $paymentIntent->amount / 100,
                        "currency" => $paymentIntent->currency,
                        "status" => "paid"
                    ]);
            
                    $store_data["status"] = "active";
                    $store_data["updated_at"] = date("Y-m-d H:i:s");
                    $store_settings = $db->update( "subscription",
                        $store_data, array("stripe_customer_id" => $customer_id)
                    );
                    
                    // $getSubscription = $db->select("subscription","*" ,array( "stripe_customer_id" => $customer_id ));
                    
                    // $stripe_subscription_id = $getSubscription['stripe_subscription_id'];
                    
                    $store_settings = $db->insert( "subscription_payments", array(
                        "subscription_id" => $stripe_subscription_id,
                        "price" => $paymentIntent->amount / 100,
                        "status" => "paid",
                        "created_at" => date("Y-m-d H:i:s")
                    ));
                    break;
                }
                default:{
                    
                    writeLog($stripe_subscription_id, "Payment successfull inside Default condition run and status is deactive in db", [
                            "amount_paid" => $paymentIntent->amount / 100,
                            "currency" => $paymentIntent->currency,
                            "status" => "failed"
                        ]);
                        
                    $store_data["status"] = "deactive";
                    $store_data["updated_at"] = date("Y-m-d H:i:s");
                    $store_settings = $db->update( "subscription",
                        $store_data, array("stripe_customer_id" => $customer_id)
                    );
                    $store_settings = $db->insert( "subscription_payments", array(
                        "subscription_id" => json_encode($paymentIntent),
                        "price" => 0,
                        "status" => "failed",
                        "created_at" => date("Y-m-d H:i:s")
                    ));                  
                }	
            }
        }
        else if($paymentIntent->type == "customer.subscription.deleted"){
            $sub_amount = $paymentIntent->plan->amount;
            // if($app_subscription_amount == $sub_amount){
            //     $channel_id = $db->getSingleColumn( "subscription", "channel_id", array( "stripe_customer_id" => $customer_id ));

            //     $getSubscriptions = $db->query("SELECT * from subscription where store_id = '$store_id' and channel_id != $channel_id and status = 'active'");
            //     if($getSubscriptions){
            //         try{
            //             if($getSubscriptions[0]){
            //                 $getSubscriptions = $getSubscriptions[0];
            //             }
                        
            //             $stripe_obj = new \Stripe\StripeClient(
            //                 $stripe['secret_key']
            //             ); 
            //             $priceObj = \Stripe\Price::create([
            //                 'unit_amount' => $app_subscription_amount * 100,
            //                 'currency' => 'usd',
            //                 'recurring' => ['interval' => 'month'],
            //                 'product_data' => ['name' => 'Regular Subscription for BC Promotions App'],
            //             ]);
            //             $stripe->subscriptions->update(
            //                 $getSubscriptions["stripe_subscription_id"],
            //                 ['items' => [['price' => $priceObj->id]]],
            //             );
            //         }
            //         catch(Exception $e){

            //         }
            //     }
            // }
            
            
            writeLog($stripe_subscription_id, "Else if run (customer.subscription.deleted and status in db is deactive)", [
                "amount_paid" => $paymentIntent->amount / 100,
                "currency" => $paymentIntent->currency,
                "status" => "deleted"
            ]);
            
            $store_data["status"] = "deactive";
            $store_data["updated_at"] = date("Y-m-d H:i:s");
            $store_settings = $db->update( "subscription",
                $store_data, array("stripe_customer_id" => $customer_id)
            );
            $store_settings = $db->insert( "subscription_payments", array(
                "subscription_id" => json_encode($paymentIntent),
                "price" => 0,
                "status" => "failed",
                "created_at" => date("Y-m-d H:i:s")
            ));
        }
    }
?>