<?php
// Auto Drive Sync Script
// Call via cron or URL every 10 minutes
// Cron: */10 * * * * php /path/to/telecom/cron_drive_sync.php
// OR: Add to cPanel Cron Jobs: */10 * * * * curl -s https://p1.enotice.top/telecom/cron_drive_sync.php?secret=YOUR_SECRET

define('CRON_SECRET', 'priyotelecom2024'); // Change this!

// Security check
$isWeb  = php_sapi_name() !== 'cli';
$secret = $_GET['secret'] ?? '';
if ($isWeb && $secret !== CRON_SECRET) {
    http_response_code(403);
    die('Forbidden');
}

require_once __DIR__.'/includes/config.php';
require_once __DIR__.'/includes/successtopup.php';
require_once __DIR__.'/includes/ecare.php';

$db = getDB();

// Check if auto sync enabled
$autoSync    = getSetting('drive_auto_sync') ?: '0';
$autoSyncApi = getSetting('drive_auto_sync_api') ?: 'successtopup';
$lastSync    = getSetting('drive_last_sync') ?: '';

if ($autoSync !== '1') {
    echo "Auto sync disabled.\n"; exit;
}

// Check if 10 minutes passed since last sync
if ($lastSync) {
    $lastTime = strtotime($lastSync);
    $diff = time() - $lastTime;
    if ($diff < 590) { // 590 seconds = ~10 min (allow 10s buffer)
        echo "Last sync was ".round($diff/60,1)." min ago. Skipping.\n"; exit;
    }
}

$added = 0; $updated = 0; $deleted = 0;
$opList = ['GP','BL','RB','AL','TT'];
$log = [];

foreach ($opList as $opCode) {
    $opRow = $db->prepare("SELECT id FROM operators WHERE UPPER(code)=? LIMIT 1");
    $opRow->execute([strtoupper($opCode)]);
    $opId = $opRow->fetchColumn() ?: null;

    if ($autoSyncApi === 'successtopup') {
        $apiResult = successTopupDriveList($opCode);
        if (empty($apiResult['result']) || empty($apiResult['drives'])) {
            $log[] = "ST $opCode: No data";
            continue;
        }

        // Delete old ST packages for this operator
        if ($opId) {
            $stmt = $db->prepare("DELETE FROM drive_packages WHERE operator_id=? AND api_package_id IS NOT NULL AND api_package_id NOT LIKE 'ECARE_%'");
            $stmt->execute([$opId]);
            $deleted += $stmt->rowCount();
        }

        foreach ($apiResult['drives'] as $ap) {
            if (!is_array($ap)) continue;
            $apiId   = strval($ap['driveId']??'');
            $apName  = preg_replace('/\s*-\s*\(ALL BD\)\s*$/', '', trim($ap['title']??'Package'));
            $apOp    = strtoupper($ap['operator']??$opCode);
            $apPrice = floatval($ap['price']??0);
            $apComm  = floatval($ap['commission']??0);
            $apValid = ($ap['duration']??'30').' Days';
            if (!$apiId || !$apPrice) continue;

            $titleLow = strtolower($apName);
            $apType   = (strpos($titleLow,'min')!==false && strpos($titleLow,'gb')!==false) ? 'combo' : (strpos($titleLow,'gb')!==false ? 'data' : 'voice');
            preg_match('/(\d+[\.\d]*\s*GB)/i',$apName,$dm);
            preg_match('/(\d+[\.\d]*\s*MIN)/i',$apName,$vm);
            $apData=$dm[1]??''; $apVoice=$vm[1]??'';

            // Insert fresh (deleted old ones above)
            $db->prepare("INSERT INTO drive_packages (name,operator_id,type,data_amount,voice_minutes,validity,api_price,commission_percent,price,cashback_amount,api_package_id,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,'active')")
               ->execute([$apName,$opId,$apType,$apData,$apVoice,$apValid,$apPrice,0,$apPrice,$apComm,$apiId]);
            $added++;
        }
        $log[] = "ST $opCode: +$added pkgs";

    } elseif ($autoSyncApi === 'ecare') {
        $res = ecareOfferPacks($opCode);
        if (empty($res['STATUS']) || $res['STATUS'] !== 'OK') {
            $log[] = "EC $opCode: Error - ".($res['MESSAGE']??'no data');
            continue;
        }
        $items = $res[$opCode] ?? [];
        if (!is_array($items) || empty($items)) {
            $log[] = "EC $opCode: Empty";
            continue;
        }

        // Delete old ECARE packages for this operator
        if ($opId) {
            $stmt = $db->prepare("DELETE FROM drive_packages WHERE operator_id=? AND api_package_id LIKE 'ECARE_%'");
            $stmt->execute([$opId]);
            $deleted += $stmt->rowCount();
        }

        foreach ($items as $idx => $ap) {
            if (!is_array($ap) || ($ap['_status']??'') !== 'A') continue;
            $apPrice  = floatval($ap['_amount']??0);
            $apComm   = floatval(str_replace(',','',$ap['_commission_amount']??0));
            $apValid  = $ap['_validity']??'30 Days';
            $apData   = $ap['_internet_pack']??'';
            $apVoice  = $ap['_minute_pack']??'';
            if (!$apPrice) continue;

            $hasData  = ($apData && $apData !== '-');
            $hasVoice = ($apVoice && $apVoice !== '-');
            $apType   = ($hasData && $hasVoice)?'combo':($hasData?'data':'voice');
            $nameParts = [];
            if ($hasData)  $nameParts[] = $apData;
            if ($hasVoice) $nameParts[] = $apVoice.' Min';
            if (empty($nameParts)) $nameParts[] = '৳'.$apPrice.' Pack';
            $apName = implode(' + ',$nameParts).' ('.$apValid.')';
            $apiId  = 'ECARE_'.$opCode.'_'.md5($apName.$apPrice);

            $db->prepare("INSERT INTO drive_packages (name,operator_id,type,data_amount,voice_minutes,validity,api_price,commission_percent,price,cashback_amount,api_package_id,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,'active')")
               ->execute([$apName,$opId,$apType,$apData,$apVoice,$apValid,$apPrice,0,$apPrice,$apComm,$apiId]);
            $added++;
        }
        $log[] = "EC $opCode: +$added pkgs";
    }
}

// Save last sync time and log
$db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['drive_last_sync',date('Y-m-d H:i:s'),date('Y-m-d H:i:s')]);
$logMsg = "Sync done [".date('Y-m-d H:i:s')."]: Deleted=$deleted, Added=$added | ".implode(', ',$log);
$db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['drive_last_sync_log',$logMsg,$logMsg]);

echo $logMsg."\n";
