<?php
set_time_limit(0);
ini_set('memory_limit', '1024M');

include "config.php";

$destdir  = "live-data-migration-csvs/";
$name     = "set_p.csv";
$destfile = $destdir . $name;

$updated = 0;
$skipped = 0;
$not_found = [];

$fp = fopen($destfile, 'r');

if (!$fp) {
    die("Unable to open CSV file");
}

// Skip header
$header = fgetcsv($fp, 1000000, ',');

while (($buffer = fgetcsv($fp, 1000000, ',')) !== false) {

    $buffer = array_map('trim', $buffer);

    // Skip empty row
    if (count(array_filter($buffer)) == 0) {
        continue;
    }

    // Excel columns
    list($set_no, $set_desc) = $buffer;

    if(empty($set_no) || empty($set_desc)){
        $skipped++;
        continue;
    }



    // Check if description exists
$query = "
    SELECT id 
    FROM set_mangmnt 
    WHERE description = '$set_desc'
";

//echo $query;   // this will print the query

$check = mysqli_query($conn, $query);

    if(mysqli_num_rows($check) > 0){

        $row = mysqli_fetch_assoc($check);
        $set_id = $row['id'];

        // Update set number
        $update = "
            UPDATE set_mangmnt
            SET set_number='$set_no'
            WHERE id='$set_id'
        ";

        if(mysqli_query($conn,$update)){
            $updated++;
        }else{
            $skipped++;
        }

    }else{

        $not_found[] = $set_desc;
        $skipped++;
    }
}

fclose($fp);

echo "<br><span style='color:green;font-weight:bold;'>$updated records updated</span>";
echo "<br><span style='color:red;font-weight:bold;'>$skipped records skipped</span>";

if(!empty($not_found)){

    $not_found = array_unique($not_found);

    echo "<br><br><span style='color:red;font-weight:bold;'>Descriptions not found:</span><br>";

    foreach($not_found as $desc){
        echo $desc."<br>";
    }
}
?>