Files
Siro/backend/bot/cron_empty_results_to_db.php
2026-06-30 14:32:39 +03:00

76 lines
2.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* cron_empty_results_to_db.php
* سكربت لتفريغ نتائج البوت من ملف results.json إلى قاعدة بيانات MySQL
* يُفضل تشغيله برمجياً كل ساعة أو حسب الحاجة
*/
// Allow script to run indefinitely
set_time_limit(0);
ini_set('memory_limit', '256M');
// Mock request to satisfy connect.php dependencies if any
$_SERVER['REQUEST_METHOD'] = 'POST';
require_once __DIR__ . '/../core/bootstrap.php';
require_once __DIR__ . '/../functions.php';
try {
$con = Database::get('main');
} catch (Exception $e) {
die("Database connection failed: " . $e->getMessage() . "\n");
}
$resultsFile = __DIR__ . '/results.json';
if (!file_exists($resultsFile)) {
die("No results file found.\n");
}
$content = file_get_contents($resultsFile);
$data = json_decode($content, true);
if (empty($data) || !is_array($data)) {
die("No data to process or invalid JSON.\n");
}
$insertedCount = 0;
$stmt = $con->prepare("INSERT INTO scraped_competitor_prices (task_id, app_name, start_location, end_location, price_amount, currency) VALUES (?, ?, ?, ?, ?, ?)");
foreach ($data as $row) {
$taskId = $row['task_id'] ?? null;
$appName = $row['app'] ?? 'Unknown';
$startLoc = $row['start_location'] ?? '';
$endLoc = $row['end_location'] ?? '';
$priceStr = $row['price'] ?? '';
// Extract numeric amount and currency from string like "2.5 JOD"
$amount = 0.0;
$currency = 'JOD';
// Match numeric parts (including decimals) and text parts
if (preg_match('/([\d\.]+)\s*([A-Za-z]+|د\.ا)/', $priceStr, $matches)) {
$amount = (float)$matches[1];
$currency = $matches[2];
if ($currency === 'د.ا') {
$currency = 'JOD';
}
} else {
$amount = (float)$priceStr;
}
// Ignore invalid entries without an amount
if ($amount <= 0) {
continue;
}
if ($stmt->execute([$taskId, $appName, $startLoc, $endLoc, $amount, $currency])) {
$insertedCount++;
}
}
// Clear the JSON file after successfully inserting data
file_put_contents($resultsFile, json_encode([], JSON_PRETTY_PRINT));
echo "Successfully inserted $insertedCount records into the database and cleared results.json.\n";