<?php
require("../connection.php");
include("../user.php");
session_start();

// error_reporting(E_ALL);
// ini_set('display_errors', '1');
?>
<link rel="stylesheet" href="../css/sweet-alert.css" /> 

<?php
$cur_date = date('Y-m-d H:i:s');
$user = $_SESSION['user'];
$branch_id = $_SESSION['branch_id'];
$ho_access = $_SESSION['ha'];

function normalize_string($str) {
    return strtolower(preg_replace('/\s+/', ' ', trim($str)));
}

// Map creation with normalized keys
function getMasterMap($result, $keyIndex = 1) {
    $map = [];
    foreach ($result as $row) {
        $map[normalize_string($row[$keyIndex])] = $row[0];
    }
    return $map;
}

$row = mysqli_fetch_array(mysqli_query($con, "SELECT id,file_name,file_path FROM admin_upload_file_master WHERE id='5'"));
$department = mysqli_fetch_all(mysqli_query($con, "SELECT id, LOWER(type) AS type FROM type_master WHERE status = 0"));
$branch = getMasterMap(mysqli_fetch_all(mysqli_query($con, "SELECT id, location FROM location_master WHERE status = 0")));
$division = getMasterMap(mysqli_fetch_all(mysqli_query($con, "SELECT id, branch_name FROM branch_master WHERE status = 0")));
$stock = mysqli_fetch_all(mysqli_query($con, "SELECT id, LOWER(category_type) AS category_type FROM category_master WHERE status = 0"));
$measurement = mysqli_fetch_all(mysqli_query($con, "SELECT id, LOWER(name) AS name FROM measurement_master WHERE status = 0"));

$id = $row['id'];

if (isset($_POST["submit"])) {
    $filename = $_FILES["file"]["tmp_name"];
    $file = fopen($filename, "r");
    $heading = true;

    while (($emapData = fgetcsv($file, 1024))) {
        if ($heading) {
            $heading = false;
            continue;
        }
        
        $dateString = trim($emapData[0]);
$formats = ['d/m/Y', 'd-m-Y', 'd.m.Y', 'd.m.y', 'j/n/Y', 'j-n-Y']; // Added variations for single-digit days/months
$so_date = null;

foreach ($formats as $format) {
    $dateObj = DateTime::createFromFormat($format, $dateString);
    if ($dateObj && $dateObj->format($format) === $dateString) {
        $so_date = $dateObj->format('Y-m-d');
        break;
    }
}


        // if ($id == 5 && $emapData[0] !== '' && $emapData[1] !== '') {
            $qumIndex = array_search(trim(strtolower($emapData[5])), array_column($measurement, 1));
$deptIndex = array_search(trim(strtolower($emapData[6])), array_column($department, 1));
$stockValue = trim(strtolower($emapData[3]));
$stockIndex = array_search($stockValue, array_column($stock, 1));

// Only set $stk if not empty and found in stock array
if ($stockValue !== '' && $stockIndex !== false) {
    $stk = $stock[$stockIndex][0];
} else {
    $stk = ''; // Or NULL, depending on what your DB expects
}
$qum = ($qumIndex !== false) ? $measurement[$qumIndex][0] : '';
$dept = ($deptIndex !== false) ? $department[$deptIndex][0] : '';

                
                $brnch_name = normalize_string($emapData[7] ?? '');
                $divsn_name = normalize_string($emapData[8] ?? '');
                $brnch = $branch[$brnch_name] ?? 0;
                $divsn = $division[$divsn_name] ?? 0;

                
                $total_amount = floatval(str_replace(',', '', trim($emapData[13] ?? '0')));

                $sql = "INSERT INTO outward_master (
                            so_date, mr_no, ticket_no, material_name, qty, qum, department, branch, division,
                            technician, approved_by, purpose, value, total_amount, status, created_on, created_by
                        ) VALUES (
                            '$so_date', 
                            '" . mysqli_real_escape_string($con, $emapData[1]) . "', 
                            '" . mysqli_real_escape_string($con, $emapData[2]) . "', 
                            '$stk', 
                            '" . mysqli_real_escape_string($con, $emapData[4]) . "', 
                            '$qum', 
                            '$dept', 
                            '$brnch', 
                            '$divsn', 
                            '" . mysqli_real_escape_string($con, $emapData[9]) . "', 
                            '" . mysqli_real_escape_string($con, $emapData[10]) . "', 
                            '" . mysqli_real_escape_string($con, $emapData[11]) . "', 
                            '" . mysqli_real_escape_string($con, $emapData[12]) . "', 
                            '$total_amount',
                            0, 
                            NOW(), 
                            '$user'
                        )";
                mysqli_query($con, $sql) or die("Insert Error: " . mysqli_error($con));
            // }
        // }
    }
    fclose($file);
}
?>

<script src="../js/sweet-alert.js"></script>
<script>
setTimeout(function () {
    swal({
        title: "Bulk Upload Log",
        text: "Uploaded",
        type: "success"
    }, function () {
        window.location = "outward_master.php";
    });
}, 100);
</script>
