<?php
// ─────────────────────────────────────────────────────────────
//  lib/StripeBooking.php — Stripe checkout + webhook handler
// ─────────────────────────────────────────────────────────────
if (!defined('DB_HOST')) require_once dirname(__DIR__) . '/lib.php';

class StripeBooking {

    public static function createCheckout(
        int    $planId,
        string $email,
        string $name,
        string $successUrl,
        string $cancelUrl
    ): string {
        if (!class_exists('\Stripe\Stripe')) {
            throw new \Exception('Stripe SDK not installed. Run: composer require stripe/stripe-php');
        }

        \Stripe\Stripe::setApiKey(defined('STRIPE_SECRET_KEY') ? STRIPE_SECRET_KEY : '');

        // Get plan
        $plan = db()->prepare('SELECT * FROM bk_plans WHERE id=? AND is_active=1');
        $plan->execute([$planId]);
        $p = $plan->fetch();
        if (!$p) throw new \Exception('Plan not found');

        $session = \Stripe\Checkout\Session::create([
            'customer_email'         => $email,
            'payment_method_types'   => ['card'],
            'line_items'             => [[
                'price_data' => [
                    'currency'     => defined('STRIPE_CURRENCY') ? STRIPE_CURRENCY : 'usd',
                    'unit_amount'  => (int)($p['price'] * 100),
                    'product_data' => [
                        'name'        => $p['name'],
                        'description' => $p['description'] ?? '',
                    ],
                ],
                'quantity' => 1,
            ]],
            'mode'        => 'payment',
            'success_url' => $successUrl . '?session_id={CHECKOUT_SESSION_ID}',
            'cancel_url'  => $cancelUrl,
            'metadata'    => [
                'plan_id'        => $planId,
                'customer_email' => $email,
                'customer_name'  => $name,
            ],
        ]);

        return $session->url;
    }

    public static function handleWebhook(string $payload, string $sigHeader): void {
        if (!class_exists('\Stripe\Stripe')) {
            throw new \Exception('Stripe SDK not installed');
        }

        $secret = defined('STRIPE_WEBHOOK_SECRET') ? STRIPE_WEBHOOK_SECRET : '';
        \Stripe\Stripe::setApiKey(defined('STRIPE_SECRET_KEY') ? STRIPE_SECRET_KEY : '');

        $event = \Stripe\Webhook::constructEvent($payload, $sigHeader, $secret);

        if ($event->type === 'checkout.session.completed') {
            $session = $event->data->object;
            $meta    = $session->metadata;
            $planId  = (int) $meta->plan_id;
            $email   = $meta->customer_email;
            $name    = $meta->customer_name;

            // Get or create customer
            $custStmt = db()->prepare('SELECT id FROM bk_customers WHERE email=?');
            $custStmt->execute([$email]);
            $cust = $custStmt->fetch();
            if (!$cust) {
                db()->prepare('INSERT INTO bk_customers (email, name) VALUES (?, ?)')
                    ->execute([$email, $name]);
                $customerId = (int) db()->lastInsertId();
            } else {
                $customerId = (int) $cust['id'];
            }

            // Get plan duration
            $planStmt = db()->prepare('SELECT * FROM bk_plans WHERE id=?');
            $planStmt->execute([$planId]);
            $plan = $planStmt->fetch();
            if (!$plan) return;

            $startsAt  = date('Y-m-d H:i:s');
            $expiresAt = date('Y-m-d H:i:s', strtotime('+' . $plan['duration_days'] . ' days'));

            db()->prepare(
                'INSERT INTO bk_memberships
                 (customer_id, plan_id, starts_at, expires_at, status,
                  stripe_payment_id, stripe_session_id, activated_by)
                 VALUES (?, ?, ?, ?, "active", ?, ?, "stripe")'
            )->execute([
                $customerId, $planId, $startsAt, $expiresAt,
                $session->payment_intent, $session->id,
            ]);

            // Send confirmation email
            $html = "<h2>Membership Activated — {$plan['name']}</h2>
                     <p>Hi {$name},</p>
                     <p>Your <strong>{$plan['name']}</strong> membership is now active.</p>
                     <p>Expires: <strong>{$expiresAt}</strong></p>
                     <p><a href=\"" . APP_URL . "/book.php\">Book an appointment now →</a></p>";
            $text = "Membership Active — {$plan['name']}\nExpires: {$expiresAt}\nBook: " . APP_URL . "/book.php";
            try {
                send_mail($email, $name, "Membership Active — {$plan['name']}", $html, $text);
            } catch (\Throwable $e) {
                error_log('Booking email error: ' . $e->getMessage());
            }
        }
    }
}
