<?php
/**
 * Generate WhatsApp Link Code
 * GET /v1/whatsapp/link-code
 * 
 * Generates a one-time code that the user sends to the WhatsApp bot
 * to link their phone number with their Musadaq account.
 */

use App\Core\Database;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();
$db = Database::getInstance();

$userId = $decoded['user_id'];

try {
    // Generate a short, easy-to-type code
    $code = strtoupper(substr(md5($userId . time() . random_int(1000, 9999)), 0, 6));

    // Save the code (expires in 10 minutes)
    $stmt = $db->prepare("UPDATE users SET whatsapp_link_code = ? WHERE id = ?");
    $stmt->execute([$code, $userId]);

    json_success([
        'code' => $code,
        'expires_in' => 600, // 10 minutes
        'instruction' => "أرسل هذه الرسالة للرقم التالي على واتساب:\n\nربط {$code}",
        'bot_number' => env('WHATSAPP_BOT_NUMBER', '+962XXXXXXXXX'),
    ], 'تم إنشاء كود الربط');

} catch (\Exception $e) {
    safe_error($e, 'whatsapp/link-code', 'حدث خطأ في إنشاء كود الربط.');
}
