<?php
include_once 'global.php';

if (isset($_POST['import_csv'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0) {
        $fileTmpPath = $_FILES['csv_file']['tmp_name'];
        $csvData = file($fileTmpPath);

        if ($csvData !== false) {
            echo "<h3>Processing CSV...</h3><pre>";

            $csvRows = array_slice($csvData, 1);

            foreach ($csvRows as $line) {
                $values = str_getcsv($line);

                $company = "Imedia";
                $domain = trim($values[0]);
                $spacefeature = trim($values[1]);
                $invfor = trim($values[2]);
                $startdate = formatDate($values[3]);
                $expirydate = formatDate($values[4]);
                $invoicedate = formatDate($values[6]);
                $vendoramount = trim($values[5]);
                $user_id = trim($values[7]);
                $array = [$company, $domain, $spacefeature, $invfor, $startdate, $expirydate, $invoicedate, $user_id, 'normal', $vendoramount, date('Y-m-d')];
                $sql = "INSERT INTO `invoices2` (`company`, `domain`, `spacefeature`, `invfor`, `startdate`, `expirydate`, `invoicedate`, `user_id`, `invtype`, `vendoramount`, `created_at`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $dbF->setRow($sql, $array);
            }

            echo "</pre>";
        } else {
            echo "Error reading CSV file.";
        }
    } else {
        echo "File upload failed.";
    }
}

function formatDate($date)
{
    $date = trim($date);
    if (!$date) return null;

    // Try multiple known formats
    $formats = ['F j, Y', 'M-d-Y', 'm/d/Y', 'Y-m-d'];
    foreach ($formats as $format) {
        $dt = DateTime::createFromFormat($format, $date);
        if ($dt !== false) {
            return $dt->format('Y-m-d');
        }
    }

    // Fallback: use strtotime
    $timestamp = strtotime($date);
    if ($timestamp !== false) {
        return date('Y-m-d', $timestamp);
    }

    return null; // If nothing worked
}
?>

<form method="post" enctype="multipart/form-data">
    <label>Select CSV file:</label>
    <input type="file" name="csv_file" accept=".csv" required>
    <button type="submit" name="import_csv">Import</button>
</form>