<?php

include_once("../public/config.php");
include("../public/include_dao.php");
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');

// No time limit for this heavy operation
set_time_limit(0);

$do = isset($_GET['do']) ? $_GET['do'] : '';

$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();

if (empty($do)) {
    @ini_set('output_buffering', 'off');
    @ini_set('zlib.output_compression', false);
    @ob_end_flush();
    header('Content-Type: text/html; charset=utf-8');
    header('X-Accel-Buffering: no');

    echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Price Fix Progress</title>';
    echo '<style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { background: #1a1a2e; color: #fff; font-family: "Segoe UI", Tahoma, Arial, sans-serif; padding: 30px; direction: rtl; }
        .container { max-width: 700px; margin: 0 auto; }
        h2 { color: #e94560; margin-bottom: 20px; }
        .progress-wrap { background: rgba(255,255,255,0.06); border-radius: 12px; overflow: hidden; height: 40px; margin: 20px 0; position: relative; }
        .progress-bar { height: 100%; background: linear-gradient(90deg, #4ecca3, #36b389); border-radius: 12px; transition: width 0.3s; min-width: 2%; }
        .progress-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); font-weight: bold; font-size: 16px; color: #fff; text-shadow: 0 1px 3px rgba(0,0,0,0.5); direction: ltr; }
        .stats { display: flex; gap: 15px; margin: 20px 0; }
        .stat { flex: 1; background: rgba(255,255,255,0.06); border-radius: 10px; padding: 15px; text-align: center; }
        .stat .val { font-size: 24px; font-weight: bold; color: #4ecca3; }
        .stat .lbl { font-size: 12px; color: rgba(255,255,255,0.4); margin-top: 5px; }
        .log { background: rgba(0,0,0,0.3); border-radius: 10px; padding: 15px; max-height: 300px; overflow-y: auto; font-family: monospace; font-size: 13px; direction: ltr; text-align: left; }
        .log .row { padding: 3px 0; border-bottom: 1px solid rgba(255,255,255,0.03); }
        .log .ok { color: #4ecca3; }
        .log .err { color: #e94560; }
        .done-box { background: rgba(78,204,163,0.15); border: 2px solid #4ecca3; border-radius: 12px; padding: 25px; text-align: center; margin-top: 20px; }
        .done-box h3 { color: #4ecca3; font-size: 22px; }
    </style></head><body><div class="container">';
    echo '<h2>&#9881; تحديث اسعار المنتجات</h2>';
    echo '<div class="stats"><div class="stat"><div class="val" id="totalVal">0</div><div class="lbl">اجمالي المنتجات</div></div><div class="stat"><div class="val" id="doneVal">0</div><div class="lbl">تم تحديثه</div></div><div class="stat"><div class="val" id="timeVal">0s</div><div class="lbl">الوقت</div></div></div>';
    echo '<div class="progress-wrap"><div class="progress-bar" id="pBar" style="width:0%"></div><div class="progress-text" id="pText">0%</div></div>';
    echo '<div class="log" id="logBox"></div>';
    echo str_pad('', 4096) . "\n"; // Force buffer flush
    flush();

    $started_at = microtime(true);
    $count = 0;
    $errors = 0;
    $start = 0;
    $limit = 100; // Bigger batches = fewer DB connections = faster
    $all_products_count = $productExt->getProductsCount();
    $total = intval($all_products_count->productId);
    $batch = 0;
    $totalBatches = ceil($total / $limit);

    echo '<script>document.getElementById("totalVal").textContent="' . $total . '";</script>';
    echo str_pad('', 256) . "\n";
    flush();

    // Single DB connection for all batches
    $conn = mysqli_connect(ConnectionProperty::getHost(), ConnectionProperty::getUser(), ConnectionProperty::getPassword(), ConnectionProperty::getDatabase());
    if (!$conn) {
        echo '<script>document.getElementById("logBox").innerHTML=\'<div class="row err">DB Connection Failed!</div>\';</script>';
        echo '</div></body></html>';
        exit;
    }

    for ($i = $start; $i <= $total; $i += $limit) {
        $batch++;
        $allproduct = $productExt->queryAllOrderedLimitedSimple($start, $limit);
        $update_sql = '';
        $batchCount = 0;
        foreach ($allproduct as $value) {
            $value->productSellHalfPrice = $value->productSellAllPrice * 1.12;
            $value->productSellUnitPrice = $value->productSellAllPrice * 1.3;
            $update_sql .= "UPDATE product SET productSellHalfPrice = $value->productSellHalfPrice, productSellUnitPrice = $value->productSellUnitPrice WHERE productId = $value->productId;";
            $count++;
            $batchCount++;
        }
        if ($update_sql != "") {
            $res = mysqli_multi_query($conn, $update_sql);
            if (!$res) {
                $errors++;
                echo '<script>document.getElementById("logBox").innerHTML += \'<div class="row err">Batch ' . $batch . ' ERROR: ' . addslashes(mysqli_error($conn)) . '</div>\';document.getElementById("logBox").scrollTop=99999;</script>';
            } else {
                while (mysqli_next_result($conn)) {;}
                echo '<script>document.getElementById("logBox").innerHTML += \'<div class="row ok">Batch ' . $batch . '/' . $totalBatches . ' — ' . $batchCount . ' products (ID ' . $start . '-' . ($start + $batchCount) . ')</div>\';document.getElementById("logBox").scrollTop=99999;</script>';
            }
        }

        $pct = min(100, round(($count / max($total, 1)) * 100));
        $elapsed = round(microtime(true) - $started_at, 1);
        echo '<script>document.getElementById("pBar").style.width="' . $pct . '%";document.getElementById("pText").textContent="' . $pct . '%";document.getElementById("doneVal").textContent="' . $count . '";document.getElementById("timeVal").textContent="' . $elapsed . 's";</script>';
        echo str_pad('', 256) . "\n";
        flush();

        $start += $limit;
    }

    mysqli_close($conn);

    $totalTime = round(microtime(true) - $started_at, 2);
    echo '<div class="done-box"><h3>&#9989; تم التحديث بنجاح</h3><p style="margin-top:10px;color:rgba(255,255,255,0.6);">' . $count . ' منتج تم تحديثه في ' . $totalTime . ' ثانية</p>';
    if ($errors > 0) {
        echo '<p style="color:#e94560;margin-top:8px;">' . $errors . ' خطأ</p>';
    }
    echo '</div></div></body></html>';
}
?>
