<?php
// webhooks/app_uninstalled.php — Handle Shopify app/uninstalled webhook
// Register this URL in your Shopify Partner Dashboard under Webhooks

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../helpers.php';

// Read raw body
$payload   = file_get_contents('php://input');
$hmacHeader = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] ?? '';

// Verify HMAC
$computedHmac = base64_encode(hash_hmac('sha256', $payload, SHOPIFY_API_SECRET, true));
if (!hash_equals($computedHmac, $hmacHeader)) {
    http_response_code(401);
    exit('Unauthorized');
}

$data = json_decode($payload, true);
$shopDomain = $_SERVER['HTTP_X_SHOPIFY_SHOP_DOMAIN'] ?? ($data['myshopify_domain'] ?? '');

if (empty($shopDomain)) {
    http_response_code(400);
    exit('Missing shop domain');
}

$db = getDB();

// Mark store as uninstalled
$stmt = $db->prepare("
    UPDATE stores SET is_active = 0, uninstalled_at = NOW(), updated_at = NOW()
    WHERE shop_domain = ?
");
$stmt->execute([$shopDomain]);

// Cancel any active subscriptions in our DB
$stmt = $db->prepare("
    UPDATE subscriptions SET status = 'cancelled', cancelled_at = NOW(), updated_at = NOW()
    WHERE store_id = (SELECT id FROM stores WHERE shop_domain = ?)
      AND status IN ('active', 'authenticated', 'pending')
");
$stmt->execute([$shopDomain]);

// Optionally cancel the Razorpay subscription via API
$subStmt = $db->prepare("
    SELECT razorpay_subscription_id FROM subscriptions
    WHERE store_id = (SELECT id FROM stores WHERE shop_domain = ?)
      AND razorpay_subscription_id IS NOT NULL
    ORDER BY created_at DESC LIMIT 1
");
$subStmt->execute([$shopDomain]);
$razorpaySubId = $subStmt->fetchColumn();

if ($razorpaySubId) {
    $url = "https://api.razorpay.com/v1/subscriptions/{$razorpaySubId}/cancel";
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_USERPWD        => RAZORPAY_KEY_ID . ':' . RAZORPAY_KEY_SECRET,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS     => json_encode(['cancel_at_cycle_end' => 0]),
    ]);
    curl_exec($ch);
    curl_close($ch);
}

error_log("App uninstalled for shop: {$shopDomain}");
http_response_code(200);
echo json_encode(['status' => 'ok']);
