<?php
/**
 * معالجة Webhook من Stripe عند اكتمال الدفع
 * يجب إضافة الرابط في Stripe Dashboard: https://your-domain.com/payment_webhook.php
 */
$config = require __DIR__ . '/config/config.php';
require_once __DIR__ . '/src/Core/Database.php';
$db = \App\Core\Database::getInstance($config['db'])->connection();

$payload = file_get_contents('php://input');
$sig = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';

$settings = [];
try {
    $stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('stripe_secret_key','stripe_webhook_secret')");
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
        $settings[$r['setting_key']] = $r['setting_value'] ?? '';
    }
} catch (Throwable $e) {
    http_response_code(500);
    exit;
}

$secret = $settings['stripe_webhook_secret'] ?? '';
if ($secret === '' || $sig === '') {
    http_response_code(400);
    exit;
}

$event = null;
try {
    $pairs = [];
    foreach (explode(',', $sig) as $p) {
        $kv = explode('=', $p, 2);
        if (count($kv) === 2) $pairs[trim($kv[0])] = trim($kv[1]);
    }
    $t = $pairs['t'] ?? '';
    $v1 = $pairs['v1'] ?? '';
    if ($t !== '' && $v1 !== '') {
        $signedPayload = $t . '.' . $payload;
        $expected = hash_hmac('sha256', $signedPayload, $secret);
        if (hash_equals($expected, $v1)) {
            $event = json_decode($payload, true);
        }
    }
} catch (Throwable $e) {}

if (!$event) {
    http_response_code(400);
    exit;
}

if (($event['type'] ?? '') !== 'checkout.session.completed') {
    http_response_code(200);
    exit;
}

$session = $event['data']['object'] ?? [];
$invoiceId = (int)($session['metadata']['invoice_id'] ?? 0);
if ($invoiceId <= 0) {
    http_response_code(200);
    exit;
}

$amountPaid = (float)($session['amount_total'] ?? 0) / 100;
$currency = strtoupper($session['currency'] ?? 'usd');
if ($currency === 'IQD') $amountPaid = (float)($session['amount_total'] ?? 0);

try {
    $stmt = $db->prepare('SELECT id, paid_amount, net_amount FROM invoices WHERE id = ?');
    $stmt->execute([$invoiceId]);
    $inv = $stmt->fetch();
    if ($inv) {
        $newPaid = (float)$inv['paid_amount'] + $amountPaid;
        $net = (float)$inv['net_amount'];
        $status = $newPaid >= $net ? 'paid' : 'partial';
        $db->prepare('UPDATE invoices SET paid_amount = ? WHERE id = ?')->execute([$newPaid, $invoiceId]);
        $db->prepare('UPDATE lab_orders o JOIN invoices i ON i.order_id = o.id SET o.payment_status = ? WHERE i.id = ?')->execute([$status, $invoiceId]);
    }
} catch (Throwable $e) {}

http_response_code(200);
