<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Database connection constants
define('DB_HOST', 'localhost');
define('DB_USER', 'wiselie_nanda');
define('DB_PASS', 'Clemira123');
define('DB_NAME', 'wiselie_inventory');

// Establish database connection
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

// Include PHPSpreadsheet
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;

// Process form submission
$message = '';
if (isset($_POST['submit'])) {
    if (isset($_FILES['excel_file']) && $_FILES['excel_file']['error'] == UPLOAD_ERR_OK) {
        $file_tmp_path = $_FILES['excel_file']['tmp_name'];
        $file_name = $_FILES['excel_file']['name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Check file extension
        $allowed_extensions = ['xls', 'xlsx', 'csv'];
        if (in_array($file_ext, $allowed_extensions)) {
            try {
                // Load the spreadsheet
                $spreadsheet = IOFactory::load($file_tmp_path);
                $worksheet = $spreadsheet->getActiveSheet();
                $rows = $worksheet->toArray();

                // Remove header row if exists
                $header = array_shift($rows);
                
                // Check if header matches expected format
                $expected_header = ['part_number', 'name', 'barcode'];
                if (count(array_intersect($header, $expected_header)) < count($expected_header)) {
                    $message = '<div class="alert alert-danger">Format Excel tidak valid. Pastikan kolom: part_number, name, barcode.</div>';
                } else {
                    $success_count = 0;
                    $error_count = 0;
                    
                    // Prepare SQL statement
                    $stmt = $db->prepare("INSERT INTO generate_barcode (part_number, name, barcode) VALUES (?, ?, ?)");
                    $stmt->bind_param("sss", $part_number, $name, $barcode);
                    
                    // Process each row
                    foreach ($rows as $row) {
                        if (empty($row[0])) continue; // Skip empty rows
                        
                        $part_number = trim($row[0]);
                        $name = trim($row[1] ?? '');
                        $barcode = trim($row[2] ?? '');
                        
                        // Execute the prepared statement
                        if ($stmt->execute()) {
                            $success_count++;
                        } else {
                            $error_count++;
                            error_log("Error importing: " . $stmt->error); // Log errors
                        }
                    }
                    
                    $stmt->close();
                    
                    $message = '<div class="alert alert-success">';
                    $message .= "Import selesai: $success_count data berhasil diimpor.";
                    if ($error_count > 0) {
                        $message .= " $error_count data gagal (mungkin duplikat part_number).";
                    }
                    $message .= '</div>';
                }
            } catch (Exception $e) {
                $message = '<div class="alert alert-danger">Error: ' . $e->getMessage() . '</div>';
            }
        } else {
            $message = '<div class="alert alert-danger">Hanya file Excel (.xls, .xlsx) yang diperbolehkan.</div>';
        }
    } else {
        $message = '<div class="alert alert-danger">Silakan pilih file Excel yang valid.</div>';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Import Data Barcode ITF-14</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
    <h2>Import Data Barcode ITF-14</h2>
    
    <?php echo $message; ?>
    
    <div class="card mt-4">
        <div class="card-header">
            <h4>Upload File Excel</h4>
        </div>
        <div class="card-body">
            <form action="import_generate_itf.php" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="excel_file">Pilih File Excel</label>
                    <input type="file" class="form-control-file" id="excel_file" name="excel_file" required>
                    <small class="form-text text-muted">
                        Format kolom: <strong>part_number</strong>, <strong>name</strong>, <strong>barcode</strong> (format .xls, .xlsx)
                    </small>
                </div>
                <button type="submit" name="submit" class="btn btn-primary">Import Data</button>
                <a href="index.php" class="btn btn-secondary">Kembali ke Daftar</a>
            </form>
        </div>
    </div>
    
    <div class="card mt-4">
        <div class="card-header">
            <h4>Panduan</h4>
        </div>
        <div class="card-body">
            <ol>
                <li>Siapkan file Excel dengan kolom: <strong>part_number</strong>, <strong>name</strong>, <strong>barcode</strong></li>
                <li>Pastikan <strong>barcode</strong> sudah dalam format ITF-14 (14 digit)</li>
                <li>Klik <strong>Pilih File</strong> dan upload file Excel</li>
                <li>Klik <strong>Import Data</strong> untuk memproses</li>
            </ol>
            <p class="text-danger">Catatan: Data dengan part_number yang sudah ada akan dilewati.</p>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>