import re with open("stock.php", "r", encoding="utf-8") as f: content = f.read() # Replace block from `// Handle Import CSV` to `// Handle AJAX actions` start_marker = "// Handle Import CSV" end_marker = "// Handle AJAX actions" start_idx = content.find(start_marker) end_idx = content.find(end_marker) if start_idx == -1 or end_idx == -1: print("Could not find import_csv block") exit(1) new_import_code = """// Handle Import CSV if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'import_csv') { if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) { require_once __DIR__ . '/includes/SimpleXLSX.php'; $pdo = db(); $file_path = $_FILES['csv_file']['tmp_name']; $raw_content = file_get_contents($file_path); $rows = []; # Check if XLSX (starts with PK) if (str_starts_with($raw_content, 'PK')) { if ( $xlsx = Shuchkin\SimpleXLSX::parse($file_path) ) { $rows = $xlsx->rows(); if (count($rows) > 0) { array_shift($rows); # Remove header } } else { header('Location: stock.php?import_error=' . urlencode('خطأ في قراءة ملف الإكسل (XLSX). يرجى التأكد من أن الملف سليم.')); exit; } } else { # Treat as CSV # Remove UTF-8 BOM if present if (str_starts_with($raw_content, "\xEF\xBB\xBF")) { $raw_content = substr($raw_content, 3); } # Fix encoding for Windows-1256 (common in Arabic Excel exports) if (!mb_check_encoding($raw_content, 'UTF-8')) { $raw_content = mb_convert_encoding($raw_content, 'UTF-8', 'Windows-1256'); } # Determine delimiter by checking first line $first_line = strtok($raw_content, "\r\n"); $delimiter = ','; if ($first_line !== false && substr_count($first_line, ';') > substr_count($first_line, ',')) { $delimiter = ';'; } $clean_file = tmpfile(); fwrite($clean_file, $raw_content); rewind($clean_file); $header = fgetcsv($clean_file, 0, $delimiter); while (($row = fgetcsv($clean_file, 0, $delimiter)) !== false) { $rows[] = $row; } fclose($clean_file); } $imported = 0; $updated = 0; $pdo->beginTransaction(); try { $stmtInsert = $pdo->prepare("INSERT INTO items (sku, name, price, cost_price, base_stock, vat, category_id, supplier_id, unit_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); $stmtUpdate = $pdo->prepare("UPDATE items SET name=?, price=?, cost_price=?, base_stock=?, vat=?, category_id=?, supplier_id=?, unit_id=? WHERE sku=?"); $stmtCheck = $pdo->prepare("SELECT id FROM items WHERE sku=?"); foreach ($rows as $row) { if (count($row) < 5) continue; $sku = trim((string)$row[0]); $name = trim((string)$row[1]); if ($sku === '' || $name === '') continue; $price = (float)($row[2] ?? 0); $cost_price = (float)($row[3] ?? 0); $base_stock = (int)($row[4] ?? 0); $vat = (float)($row[5] ?? 5); $category_id = !empty($row[6]) ? (int)$row[6] : null; $supplier_id = !empty($row[7]) ? (int)$row[7] : null; $unit_id = !empty($row[8]) ? (int)$row[8] : null; $stmtCheck->execute([$sku]); if ($stmtCheck->fetchColumn()) { $stmtUpdate->execute([$name, $price, $cost_price, $base_stock, $vat, $category_id, $supplier_id, $unit_id, $sku]); $updated++; } else { $stmtInsert->execute([$sku, $name, $price, $cost_price, $base_stock, $vat, $category_id, $supplier_id, $unit_id]); $imported++; } } $pdo->commit(); header('Location: stock.php?import_success=1&imported='.$imported.'&updated='.$updated); exit; } catch (Exception $e) { $pdo->rollBack(); header('Location: stock.php?import_error='.urlencode($e->getMessage())); exit; } } header('Location: stock.php?import_error=No+file'); exit; } """ content = content[:start_idx] + new_import_code + content[end_idx:] # Update the modal text to reflect XLSX support content = content.replace("ملاحظة: يدعم النظام ملفات CSV فقط. يرجى حفظ ملف Excel بصيغة (CSV UTF-8).", "ملاحظة: يدعم النظام الآن ملفات Excel (XLSX) بالإضافة إلى CSV.") content = content.replace("Note: The system supports CSV files only. Please save your Excel file as (CSV UTF-8).", "Note: The system now supports Excel (XLSX) files in addition to CSV.") content = content.replace('accept=".csv"', 'accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"') with open("stock.php", "w", encoding="utf-8") as f: f.write(content) print("Patched successfully")