<?php
require_once('includes/load.php');
page_require_level(2);

if (isset($_POST['import_csv'])) {
    if ($_FILES['csv_file']['error'] == UPLOAD_ERR_OK && is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
        $csv_file = $_FILES['csv_file']['tmp_name'];
        $imported_sales = array();

        if (($handle = fopen($csv_file, "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
                $product_id = $data[0];
                $qty = $data[1];
                $date = $data[2];

                if (is_numeric($product_id) && is_numeric($qty) && strtotime($date)) {
                    $imported_sales[] = array(
                        'product_id' => $product_id,
                        'qty' => $qty,
                        'date' => date('Y-m-d', strtotime($date))
                    );
                }
            }
            fclose($handle);

            if (!empty($imported_sales)) {
                foreach ($imported_sales as $imported_sale) {
                    add_sale($imported_sale['product_id'], $imported_sale['qty'], $imported_sale['date']);
                }
                $session->msg('s', 'Sales data imported successfully.');
            } else {
                $session->msg('d', 'Invalid CSV format or data.');
            }
        }
    }
    redirect('sales.php', false);
} else {
    $session->msg('d', 'Invalid request for CSV import.');
    redirect('sales.php', false);
}
?>
