<?php
$page_title = 'Import Productivity Data';
require_once('includes/load.php');
page_require_level(3);

include_once('layouts/header.php');

$success_message = '';
$error_message = '';

if (isset($_POST['import_button'])) {
    if (isset($_FILES['import_csv']['tmp_name'])) {
        $file = $_FILES['import_csv']['tmp_name'];
        if (($handle = fopen($file, "r")) !== false) {
            while (($data = fgetcsv($handle, 1000, ';')) !== false) {
                if (count($data) === 6) {
                    $date = $db->escape($data[0]);
                    $work_time = $db->escape($data[1]);
                    $name = $db->escape($data[2]);
                    $color = $db->escape($data[3]);
                    $quantity = $db->escape($data[4]);
                    $work_center = $db->escape($data[5]);

                    $sql = "INSERT INTO productivity (date, work_time, name, color, quantity, work_center) VALUES ('$date', '$work_time', '$name', '$color', '$quantity', '$work_center')";
                    if ($db->query($sql)) {
                        $success_message = 'Data berhasil diimpor dari file CSV.';
                    } else {
                        $error_message = 'Terjadi kesalahan saat mengimpor data.';
                        break;
                    }
                } else {
                    $error_message = 'Format data dalam file CSV tidak sesuai.';
                    break;
                }
            }
            fclose($handle);
        } else {
            $error_message = 'Gagal membuka file CSV.';
        }
    } else {
        $error_message = 'File CSV tidak valid.';
    }
}
?>

<h1>Import Productivity Data</h1>

<?php if (!empty($success_message)): ?>
<div class="alert alert-success">
    <?php echo $success_message; ?>
</div>
<?php endif; ?>

<?php if (!empty($error_message)): ?>
<div class="alert alert-danger">
    <?php echo $error_message; ?>
</div>
<?php endif; ?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
    <div class="form-group">
        <label for="import_csv">Import CSV:</label>
        <input type="file" name="import_csv" id="import_csv" accept=".csv">
    </div>
    <input type="submit" value="Import" name="import_button">
</form>

<?php include('layouts/footer.php'); ?>
