<?php
$page_title = 'Upload Production Schedule';
require_once('includes/load.php');
page_require_level(3); // Ensure required user level

// Variables for storing messages and data
$msg = '';

// Filter bulan
if (isset($_GET['month'])) {
    $selected_month = $_GET['month']; // Format: YYYY-MM
    $start_date = $selected_month . '-01';
    $end_date = date("Y-m-t", strtotime($start_date)); // Ambil tanggal terakhir bulan tersebut
} else {
    $start_date = date('Y-m-01'); // Default ke bulan ini
    $end_date = date('Y-m-t');
}

// Upload CSV
if (isset($_POST['upload_csv'])) {
    if (is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
        $csv_file = fopen($_FILES['csv_file']['tmp_name'], 'r');
        
        // Skip the CSV header
        fgetcsv($csv_file, 1000, ";");

        $success_count = 0;
        $error_count = 0;
        
        while (($row = fgetcsv($csv_file, 1000, ";")) !== FALSE) {
            $no_order = $db->escape($row[0]);
            $client = $db->escape($row[1]);
            $part_number = $db->escape($row[2]);
            $quantity_order = (int)$row[3];
            $delivery_date = $db->escape($row[4]);
            
            // Insert data into the database
            $query = "INSERT INTO production_schedule (no_order, client, part_number, quantity_order, delivery_date) 
                      VALUES ('{$no_order}', '{$client}', '{$part_number}', {$quantity_order}, '{$delivery_date}')";
            if ($db->query($query)) {
                $success_count++;
            } else {
                $error_count++;
            }
        }
        fclose($csv_file);
        
        if ($error_count == 0) {
            $msg = "CSV file successfully uploaded. {$success_count} records inserted.";
        } else {
            $msg = "CSV file uploaded with {$success_count} successful inserts and {$error_count} errors.";
        }
    } else {
        $msg = "Please upload a valid CSV file.";
    }
}

include_once('layouts/header.php'); 
?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <div class="pull-left">
                    <h3 class="panel-title">Upload Production Schedule - <?php echo date('F Y', strtotime($start_date)); ?></h3>
                </div>
                <div class="pull-right">
                    <a href="production_schedule.php?month=<?php echo date('Y-m', strtotime($start_date)); ?>" class="btn btn-default">
                        Back to Schedule
                    </a>
                </div>
            </div>
            <div class="panel-body">
                <form method="GET" action="upload_production_schedule.php" class="form-inline">
                    <div class="form-group">
                        <label for="month">Pilih Bulan:</label>
                        <input type="month" name="month" id="month" class="form-control" value="<?php echo isset($_GET['month']) ? $_GET['month'] : date('Y-m'); ?>">
                    </div>
                    <button type="submit" class="btn btn-primary">Filter</button>
                </form>

                <hr>

                <form action="upload_production_schedule.php?month=<?php echo date('Y-m', strtotime($start_date)); ?>" method="POST" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="csv_file">Upload CSV File:</label>
                        <input type="file" name="csv_file" id="csv_file" class="form-control" required>
                        <p class="help-block">CSV format: Order Number;Client;Part Number;Quantity;Delivery Date (YYYY-MM-DD)</p>
                    </div>
                    <button type="submit" name="upload_csv" class="btn btn-primary">Upload</button>
                    <a href="production_schedule.php?month=<?php echo date('Y-m', strtotime($start_date)); ?>" class="btn btn-default">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>

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