<?php
include("../connection.php");
include("../user.php");
session_start();
date_default_timezone_set('Asia/Kolkata');
$cur_date = date('Y-m-d H:i:s');
$user = $_SESSION['user'];
$branch_id = $_SESSION['branch_id'];
$ho_access = $_SESSION['ha'];

// Normalize function: trims, lowercases, and removes multiple spaces
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;
}

$vendors = getMasterMap(mysqli_fetch_all(mysqli_query($con, "SELECT id, vendor_name FROM vendor_master WHERE status = 0")));
$department = getMasterMap(mysqli_fetch_all(mysqli_query($con, "SELECT id, 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 = getMasterMap(mysqli_fetch_all(mysqli_query($con, "SELECT id, category_type FROM category_master WHERE status = 0")));
$measurement = getMasterMap(mysqli_fetch_all(mysqli_query($con, "SELECT id, name FROM measurement_master WHERE status = 0")));

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

        while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
            if ($heading) {
                $heading = false;
                continue;
            }

            // $dateString = trim($emapData[1]);
            // $formats = ['d/m/Y', 'd-m-Y'];
            // $po_date = null;

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



//             $dateString = trim($emapData[1]);
// $dateObj = DateTime::createFromFormat('d.m.y', $dateString);
// $po_date = $dateObj ? $dateObj->format('Y-m-d') : NULL;

            // $dateString = trim($emapData[1]);
            // $dateObj = DateTime::createFromFormat('d/m/Y', $dateString);
            // $po_date = $dateObj ? $dateObj->format('Y-m-d') : NULL;
            
            $dateString = trim($emapData[1]);
$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
$po_date = null;

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

// Optional fallback: log or skip if date parsing fails
if (!$po_date) {
    // echo "Invalid date: $dateString"; // Uncomment for debugging
    continue; // Skip this row if the date is invalid
}


            // Normalize each value before lookup
            $vendor_name = normalize_string($emapData[2] ?? '');
            $billno = trim($emapData[3] ?? '');
            $gate_entry = trim($emapData[4] ?? '');
            $material = trim($emapData[5] ?? '');

            if ($material == '')
                continue;

            $qty = floatval(str_replace(',', '', trim($emapData[6] ?? '0')));
            $qum_name = normalize_string($emapData[7] ?? '');
            $dept_name = normalize_string($emapData[8] ?? '');
            $brnch_name = normalize_string($emapData[9] ?? '');
            $divsn_name = normalize_string($emapData[10] ?? '');
            $value = floatval(str_replace(',', '', trim($emapData[11] ?? '0')));
            $amount = floatval(str_replace(',', '', trim($emapData[12] ?? '0')));
            $gst = floatval(str_replace(',', '', trim($emapData[13] ?? '0')));
            $discount = floatval(str_replace(',', '', trim($emapData[14] ?? '0')));
            $total_amount = floatval(str_replace(',', '', trim($emapData[15] ?? '0')));

            // Lookup normalized
            $vendor = $vendors[$vendor_name] ?? 0;
            $qum = $measurement[$qum_name] ?? 0;
            $dept = $department[$dept_name] ?? 0;
            $brnch = $branch[$brnch_name] ?? 0;
            $divsn = $division[$divsn_name] ?? 0;
            $stk = $stock[normalize_string($material)] ?? 0;

            // Insert into DB
            $insert = "INSERT INTO item_master(
                                po_date, vendor_name, billno, gatentry, material_name, 
                                quantity, qum, department, branch, division, 
                                value, amount, gst_percentage, discount, total_amount, 
                                status, created_by, created_on
                            ) VALUES (
                                '$po_date', '$vendor', '$billno', '$gate_entry', '$stk', 
                                '$qty', '$qum', '$dept', '$brnch', '$divsn', 
                                '$value', '$amount', '$gst', '$discount', '$total_amount', 
                                0, '$user', '$cur_date'
                            )";
            mysqli_query($con, $insert);
        }
        fclose($file);
    }
}
?>
<!-- Sweet Alert -->
<script src="../js/sweet-alert.js"></script>
<link rel="stylesheet" href="../css/sweet-alert.css" />
<script>
    setTimeout(function () {
        swal({
            title: "Upload Completed",
            text: "Inward material data imported successfully.",
            type: "success"
        }, function () {
            window.location = "inward_master.php";
        });
    }, 100);
</script>