<?php
require "commonincludefiles.php";
require_once "phpspreadsheet/autoload.php";

use PhpOffice\PhpSpreadsheet\IOFactory;

ini_set('memory_limit', '-1');

// Check for file upload errors
if ($_FILES['enrollment_upload']['error'] != UPLOAD_ERR_OK) {
    echo json_encode(["success" => "false", "msg" => "File upload failed."]);
    exit;
}

$fullpath = $_FILES['enrollment_upload']['tmp_name'];

// Identify file type and load spreadsheet
try {
    $inputFileType = IOFactory::identify($fullpath);
    $reader = IOFactory::createReader($inputFileType);
    $spreadsheet = $reader->load($fullpath);
} catch (Exception $e) {
    echo json_encode(["success" => "false", "msg" => "Error loading the file: " . $e->getMessage()]);
    exit;
}

// Get the active sheet and convert it to array
$worksheet = $spreadsheet->getActiveSheet();
$exceldata = $worksheet->toArray();

// Check if there's data in the file
$total = count($exceldata);
if ($total < 1) {
    echo json_encode(["success" => "false", "msg" => "No data found in the file."]);
    exit;
}

// Continue with further processing...
$sql = "INSERT INTO `csc_customer`( 
    `sr_no`, `company_name`, `csc_id`, `estore_name`, `vendor_name`, `estore_phoneno`, 
    `alternate_number`, `document_type`, `document_no`, `vendor_email`, `distributor_name`, 
    `distributor_phoneno`, `order_no`, `address`, `address1`, `district`, `state`, `gst_no`, 
    `product_name`, `sku`, `quantity`, `mrp`, `payment_date`, `payment_mode`, `order_status`, 
    `order_date`, `transcation_id`, `gatway_id`, `transcation_date`, `transcation_status`, 
    `master_distribution`, `invoice_status`, `courier_company`, `import_date` 
) VALUES ";

for ($j = 0; $j < $total; $j++) {
    $sql .= "(";

    for ($k = 0; $k < 33; $k++) {
        $value = Escape($exceldata[$j][$k]);

        // If value is empty, assign blank ''
        if (empty($value)) {
            $value = "''";
        } else {
            $value = "'" . $value . "'";  // Escape the data
        }

        $sql .= $value . ",";
    }

    // Append the current date for the last field
    $sql .= "'" . date('Y-m-d') . "'),";
}

// Remove the trailing comma
$sql = rtrim($sql, ",");

// Execute the SQL query
 dbQuery($sql);

    echo '{"success":"true","msg":"Total ' . ($total) . ' rows imported."}';
	exit;

?>
