<?php
require_once 'db/config.php';
require_once 'stripe-php/init.php';

// Replace with your Stripe secret key
$stripeSecretKey = 'sk_test_51SnbE1DXiGqo6jDypbXwuZkNZVV4g4KB9rkixQzchrtzzjd8kGYON1QIweBLYHG1mNqrGxjCuvQBeVRsCyhAI58400CllOBiwh';
\Stripe\Stripe::setApiKey($stripeSecretKey);

// Replace with your webhook signing secret
$webhookSecret = 'whsec_12345'; // PLACEHOLDER

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

try {
    $event = \Stripe\Webhook::constructEvent(
        $payload, $sig_header, $webhookSecret
    );
} catch(\UnexpectedValueException $e) {
    // Invalid payload
    http_response_code(400);
    exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
    // Invalid signature
    http_response_code(400);
    exit();
}

// Handle the event
switch ($event->type) {
    case 'invoice.payment_succeeded':
        $invoice = $event->data->object;
        $subscription_id = $invoice->subscription;
        
        // Get subscription details
        try {
            $subscription = \Stripe\Subscription::retrieve($subscription_id);
        } catch (\Stripe\Exception\ApiErrorException $e) {
            // Log error
            http_response_code(400);
            exit();
        }

        $end_date = date('Y-m-d H:i:s', $subscription->current_period_end);

        // Update subscription in database
        try {
            $stmt = db()->prepare("UPDATE subscriptions SET status = 'active', end_date = ? WHERE stripe_subscription_id = ?");
            $stmt->execute([$end_date, $subscription_id]);
        } catch (PDOException $e) {
            // Log error
            http_response_code(500);
            exit();
        }
        break;
    case 'customer.subscription.deleted':
        $subscription = $event->data->object;
        $subscription_id = $subscription->id;

        // Update subscription in database
        try {
            $stmt = db()->prepare("UPDATE subscriptions SET status = 'canceled' WHERE stripe_subscription_id = ?");
            $stmt->execute([$subscription_id]);
        } catch (PDOException $e) {
            // Log error
            http_response_code(500);
            exit();
        }
        break;
    default:
        // Unexpected event type
        http_response_code(200);
        exit();
}

http_response_code(200);
