<?php
header('Content-Type: application/json; charset=utf-8');

$SECRET_KEY = 'YOUR_SECRET_KEY';
$ZIBAL_MERCHANT = 'YOUR_ZIBAL_MERCHANT';
$CALLBACK_URL = 'https://violexq.ir/api/verify.php';

$db_host = 'localhost';
$db_name = 'violexst_bot';
$db_user = 'violexst_botuser';
$db_pass = 'YOUR_DB_PASSWORD';

if (($_POST['api_key'] ?? '') !== $SECRET_KEY) {
    http_response_code(403);
    echo json_encode([
        'status' => false,
        'message' => 'Unauthorized'
    ]);
    exit;
}

$user_id = $_POST['user_id'] ?? '';
$amount = intval($_POST['amount'] ?? 0);
$description = $_POST['description'] ?? 'پرداخت';
$card_id = $_POST['card_id'] ?? null;
$package_id = $_POST['package_id'] ?? null;

if (!$user_id || $amount <= 0) {
    echo json_encode([
        'status' => false,
        'message' => 'اطلاعات پرداخت نامعتبر است'
    ]);
    exit;
}

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

if ($conn->connect_error) {
    echo json_encode([
        'status' => false,
        'message' => 'خطا در اتصال به دیتابیس'
    ]);
    exit;
}

$conn->set_charset('utf8mb4');

$data = [
    'merchant' => $ZIBAL_MERCHANT,
    'amount' => $amount,
    'callbackUrl' => $CALLBACK_URL,
    'description' => $description
];

$ch = curl_init('https://gateway.zibal.ir/v1/request');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json'
    ],
    CURLOPT_TIMEOUT => 30
]);

$response = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

if ($response === false) {
    echo json_encode([
        'status' => false,
        'message' => 'خطا در ارتباط با زیبال',
        'error' => $curl_error
    ]);
    exit;
}

$result = json_decode($response, true);

if (!isset($result['trackId']) || empty($result['trackId'])) {
    echo json_encode([
        'status' => false,
        'message' => 'زیبال درخواست پرداخت را قبول نکرد',
        'response' => $result
    ]);
    exit;
}

$authority = (string)$result['trackId'];

$stmt = $conn->prepare("
    INSERT INTO payments
    (user_id, authority, amount, description, card_id, package_id, status, created_at)
    VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())
");

$stmt->bind_param(
    'ssisss',
    $user_id,
    $authority,
    $amount,
    $description,
    $card_id,
    $package_id
);

if (!$stmt->execute()) {
    echo json_encode([
        'status' => false,
        'message' => 'خطا در ذخیره پرداخت',
        'error' => $stmt->error
    ]);
    $stmt->close();
    $conn->close();
    exit;
}

$stmt->close();
$conn->close();

echo json_encode([
    'status' => true,
    'authority' => $authority,
    'payment_url' => 'https://gateway.zibal.ir/start/' . $authority
], JSON_UNESCAPED_UNICODE);
