<?php
// Webhook لإي فواتيركم - استقبال إشعارات الدفع وتحديث الحالة تلقائياً
require_once('../config/db.php'); // الاتصال بقاعدة البيانات

// --- ضع هنا المفتاح السري الذي حصلت عليه من إي فواتيركم ---
$SECRET_KEY = "ضع_هنا_المفتاح_السري";

// التحقق من مفتاح الإشعار المرسل في الهيدر
$incoming_key = $_SERVER['HTTP_X_EFAWATEER_KEY'] ?? '';
if ($incoming_key !== $SECRET_KEY) {
    http_response_code(403);
    exit('Forbidden: Invalid Key');
}

// تأكد أن الطلب POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

// قراءة بيانات POST من Webhook
$payload = file_get_contents('php://input');
$data = json_decode($payload, true);

// تحقق من صحة البيانات
if (!$data || !isset($data['invoice_id']) || !isset($data['status'])) {
    http_response_code(400);
    exit('Bad Request: Missing invoice_id or status');
}

$invoice_id  = $data['invoice_id'];
$status      = strtolower($data['status']); // paid, failed, pending
$paid_amount = floatval($data['paid_amount'] ?? 0);

try {
    // جلب الفاتورة من قاعدة البيانات
    $stmt = $conn->prepare("SELECT * FROM efawateer_invoices WHERE invoice_id = ?");
    $stmt->execute([$invoice_id]);
    $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$invoice) {
        http_response_code(404);
        exit('Invoice not found');
    }

    // تحديث حالة الفاتورة
    $update = $conn->prepare("
        UPDATE efawateer_invoices 
        SET status = ?, paid_amount = ?, updated_at = NOW() 
        WHERE id = ?
    ");
    $update->execute([$status, $paid_amount, $invoice['id']]);

    // إذا كانت الحالة مدفوعة، سجل الدفعة في جدول payments
    if ($status === 'paid') {
        $student_id = $invoice['student_id'];

        // تحقق إذا لم تُسجل هذه الدفعة مسبقاً
        $check_stmt = $conn->prepare("SELECT COUNT(*) FROM payments WHERE efawateer_invoice_id = ?");
        $check_stmt->execute([$invoice['id']]);
        $already = $check_stmt->fetchColumn();

        if (!$already) {
            $stmt_insert = $conn->prepare("
                INSERT INTO payments 
                (student_id, amount_paid, payment_date, payment_method, notes, discount, efawateer_invoice_id) 
                VALUES (?, ?, NOW(), ?, ?, ?, ?)
            ");
            $stmt_insert->execute([
                $student_id,
                $paid_amount,
                'إلكتروني',
                "دفعة إلكترونية عبر إي فواتيركم - فاتورة $invoice_id",
                0,
                $invoice['id']
            ]);
        }
    }

    // الرد لإي فواتيركم
    http_response_code(200);
    echo json_encode(['status' => 'success']);
    exit;

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    exit;
}
?>
