<?php
/**
 * core.php - কনফিগ + ডাটাবেজ + এনক্রিপশন + Steadfast API + হেল্পার (সব একসাথে)
 */
require_once __DIR__ . '/config.php';

try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    die('ডাটাবেজ সংযোগ ব্যর্থ। config.php চেক করুন। ' . $e->getMessage());
}

function encryptKey($text) {
    if (empty($text)) return null;
    $key = substr(hash('sha256', ENCRYPTION_KEY, true), 0, 32);
    $iv = random_bytes(16);
    $encrypted = openssl_encrypt($text, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($iv . $encrypted);
}

function decryptKey($encryptedText) {
    if (empty($encryptedText)) return null;
    $raw = base64_decode($encryptedText, true);
    if ($raw === false || strlen($raw) < 17) return null;
    $key = substr(hash('sha256', ENCRYPTION_KEY, true), 0, 32);
    $iv = substr($raw, 0, 16);
    $cipher = substr($raw, 16);
    $decrypted = openssl_decrypt($cipher, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return $decrypted !== false ? $decrypted : null;
}

function steadfastRequest($apiKey, $secretKey, $method, $path, $body = null) {
    $url = STEADFAST_BASE_URL . $path;
    $ch = curl_init($url);
    $headers = ['Api-Key: ' . $apiKey, 'Secret-Key: ' . $secretKey, 'Content-Type: application/json'];
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    if ($body !== null && in_array($method, ['POST', 'PUT'])) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, is_string($body) ? $body : json_encode($body));
    }
    $response = curl_exec($ch);
    $err = curl_error($ch);
    $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($err) return ['ok' => false, 'http_code' => $httpCode, 'error' => $err];
    $decoded = json_decode($response, true);
    if (!is_array($decoded)) {
        return ['ok' => $httpCode >= 200 && $httpCode < 300, 'http_code' => $httpCode, 'raw' => $response];
    }
    $decoded['ok'] = $httpCode >= 200 && $httpCode < 300;
    $decoded['http_code'] = $httpCode;
    return $decoded;
}

function steadfastCreateOrder($apiKey, $secretKey, $data) { return steadfastRequest($apiKey, $secretKey, 'POST', '/create_order', $data); }
function steadfastBulkOrder($apiKey, $secretKey, $dataArray) { return steadfastRequest($apiKey, $secretKey, 'POST', '/create_order/bulk-order', ['data' => $dataArray]); }
function steadfastStatusByCid($apiKey, $secretKey, $id) { return steadfastRequest($apiKey, $secretKey, 'GET', '/status_by_cid/' . urlencode($id)); }
function steadfastStatusByInvoice($apiKey, $secretKey, $invoice) { return steadfastRequest($apiKey, $secretKey, 'GET', '/status_by_invoice/' . urlencode($invoice)); }
function steadfastStatusByTracking($apiKey, $secretKey, $code) { return steadfastRequest($apiKey, $secretKey, 'GET', '/status_by_trackingcode/' . urlencode($code)); }
function steadfastGetBalance($apiKey, $secretKey) { return steadfastRequest($apiKey, $secretKey, 'GET', '/get_balance'); }
function steadfastCreateReturn($apiKey, $secretKey, $data) { return steadfastRequest($apiKey, $secretKey, 'POST', '/create_return_request', $data); }
function steadfastGetReturnRequests($apiKey, $secretKey) { return steadfastRequest($apiKey, $secretKey, 'GET', '/get_return_requests'); }
function steadfastGetPayments($apiKey, $secretKey) { return steadfastRequest($apiKey, $secretKey, 'GET', '/payments'); }
function steadfastGetPaymentById($apiKey, $secretKey, $paymentId) { return steadfastRequest($apiKey, $secretKey, 'GET', '/payments/' . urlencode($paymentId)); }
function steadfastGetReturnRequest($apiKey, $secretKey, $id) { return steadfastRequest($apiKey, $secretKey, 'GET', '/get_return_request/' . urlencode($id)); }
function steadfastGetPoliceStations($apiKey, $secretKey) { return steadfastRequest($apiKey, $secretKey, 'GET', '/police_stations'); }

function steadfastFriendlyMessage($result) {
    $raw = isset($result['raw']) ? (is_string($result['raw']) ? $result['raw'] : json_encode($result['raw'])) : '';
    $message = isset($result['message']) && is_string($result['message']) ? $result['message'] : '';
    $error = isset($result['error']) && is_string($result['error']) ? $result['error'] : '';
    $haystack = strtolower($raw . ' ' . $message . ' ' . $error);
    if (stripos($raw, 'Account is not active') !== false) {
        return ['success' => false, 'message' => 'আপনার Steadfast অ্যাকাউন্ট এখনও অ্যাক্টিভ হয়নি। Steadfast সাপোর্টে যোগাযোগ করুন।', 'account_inactive' => true];
    }
    if (strpos($haystack, 'unauthorized') !== false || strpos($haystack, 'invalid api') !== false || strpos($haystack, 'forbidden') !== false) {
        return ['success' => false, 'message' => 'API Key বা Secret Key ভুল। Settings থেকে সঠিক Key দিন।', 'auth_error' => true];
    }
    if (strpos($haystack, 'already exists') !== false || strpos($haystack, 'duplicate') !== false || strpos($haystack, 'invoice') !== false && strpos($haystack, 'exist') !== false) {
        return ['success' => false, 'message' => 'এই Invoice আগে থেকেই আছে। নতুন Invoice দিয়ে চেষ্টা করুন।', 'duplicate_invoice' => true];
    }
    if (strpos($haystack, 'timed out') !== false || strpos($haystack, 'timeout') !== false) {
        return ['success' => false, 'message' => 'Courier API টাইমআউট হয়েছে। একটু পরে আবার চেষ্টা করুন।', 'timeout' => true];
    }
    if (strpos($haystack, 'recipient_phone') !== false || strpos($haystack, 'validation') !== false) {
        return ['success' => false, 'message' => 'অর্ডারের কিছু তথ্য সঠিক নয়। ফোন, ঠিকানা, বা ডেলিভারি টাইপ চেক করুন।', 'validation_error' => true];
    }
    return null;
}

function normalizeCreateOrderResult($result) {
    $friendly = steadfastFriendlyMessage($result);
    if ($friendly !== null) {
        $friendly['raw'] = $result;
        return $friendly;
    }
    $consignment = isset($result['consignment']) && is_array($result['consignment']) ? $result['consignment'] : null;
    $ok = !empty($result['ok']);
    $httpCode = isset($result['http_code']) ? (int) $result['http_code'] : 0;
    $hasTracking = $consignment && !empty($consignment['tracking_code']);
    $success = ($ok && $hasTracking) || (isset($result['status']) && (int) $result['status'] === 200 && $hasTracking);
    if ($success) {
        return [
            'success' => true,
            'message' => 'অর্ডার সফল হয়েছে।',
            'tracking_code' => (string) ($consignment['tracking_code'] ?? ''),
            'consignment_id' => (string) ($consignment['consignment_id'] ?? ''),
            'status_text' => (string) ($consignment['status'] ?? ''),
            'http_code' => $httpCode,
            'raw' => $result
        ];
    }
    return [
        'success' => false,
        'message' => (string) ($result['message'] ?? $result['error'] ?? 'Courier API order create ব্যর্থ হয়েছে।'),
        'tracking_code' => '',
        'consignment_id' => '',
        'status_text' => '',
        'http_code' => $httpCode,
        'raw' => $result
    ];
}

function getUserId() {
    session_name(SESSION_NAME);
    if (session_status() === PHP_SESSION_NONE) session_start();
    return isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : null;
}

function requireLogin() {
    session_name(SESSION_NAME);
    if (session_status() === PHP_SESSION_NONE) session_start();
    if (empty($_SESSION['user_id'])) {
        header('Location: index.php');
        exit;
    }
    return (int) $_SESSION['user_id'];
}

function getUserKeys($userId) {
    global $pdo;
    $st = $pdo->prepare('SELECT api_key_encrypted, secret_key_encrypted FROM user_keys WHERE user_id = ?');
    $st->execute([$userId]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row) return null;
    $api = decryptKey($row['api_key_encrypted']);
    $secret = decryptKey($row['secret_key_encrypted']);
    if (!$api || !$secret) return null;
    return ['apiKey' => $api, 'secretKey' => $secret];
}
