<?php
require 'vendor/autoload.php'; // Load Composer autoloader
use PhpOffice\PhpSpreadsheet\IOFactory;

$page_title = 'Production Schedule';
require_once('includes/load.php');
page_require_level(3);

// Variabel pesan dan 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)); // Tanggal terakhir bulan
} else {
    $start_date = date('Y-m-01'); // Default: bulan ini
    $end_date = date('Y-m-t');
}

// Hapus semua jadwal produksi bulan terpilih
if (isset($_GET['action']) && $_GET['action'] == 'delete_all') {
    $delete_query = "DELETE FROM production_schedule WHERE delivery_date BETWEEN '{$start_date}' AND '{$end_date}'";
    if ($db->query($delete_query)) {
        $session->msg('s', "Semua jadwal produksi untuk " . date('F Y', strtotime($start_date)) . " telah dihapus.");
        redirect('production_schedule.php?month=' . date('Y-m', strtotime($start_date)), false);
    } else {
        $session->msg('d', "Gagal menghapus jadwal produksi.");
        redirect('production_schedule.php?month=' . date('Y-m', strtotime($start_date)), false);
    }
}

// Import Excel
if (isset($_POST['upload_excel'])) {
    if (is_uploaded_file($_FILES['excel_file']['tmp_name'])) {
        $filePath = $_FILES['excel_file']['tmp_name'];
        
        try {
            // Load file Excel
            $spreadsheet = IOFactory::load($filePath);
            $sheet = $spreadsheet->getActiveSheet();
            $rows = $sheet->toArray();

            // Lewati header (baris pertama)
            array_shift($rows);

            $imported_count = 0;
            $failed_count = 0;

            foreach ($rows as $row) {
                // Pastikan baris tidak kosong
                if (array_filter($row)) {
                    $no_order = $db->escape($row[0]);
                    $client = $db->escape($row[1]);
                    $part_number = $db->escape($row[2]);
                    $quantity_order = (int)$row[3];
                    
                    // Perbaikan: Konversi tanggal jika formatnya dari Excel
                    $delivery_date_raw = $row[4];
                    if (\PhpOffice\PhpSpreadsheet\Shared\Date::isExcelDate($delivery_date_raw)) {
                        $delivery_date = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($delivery_date_raw)->format('Y-m-d');
                    } else {
                        $delivery_date = $db->escape($delivery_date_raw);
                    }
                    
                    // Insert ke database
                    $query = "INSERT INTO production_schedule (no_order, client, part_number, quantity_order, delivery_date, input_date) 
                              VALUES ('{$no_order}', '{$client}', '{$part_number}', {$quantity_order}, '{$delivery_date}', NOW())";
                    
                    if ($db->query($query)) {
                        $imported_count++;
                    } else {
                        $failed_count++;
                        // Opsional: Log error spesifik jika gagal
                        // error_log("Gagal menyimpan data untuk order {$no_order}. Error: " . $db->error);
                    }
                }
            }
            
            $session->msg('s', "Impor selesai! Berhasil: {$imported_count}, Gagal: {$failed_count}.");
            redirect('production_schedule.php', false);

        } catch (Exception $e) {
            $session->msg('d', "Error saat mengimpor: " . $e->getMessage());
            redirect('production_schedule.php', false);
        }
    } else {
        $session->msg('d', "Silakan unggah file Excel yang valid.");
        redirect('production_schedule.php', false);
    }
}

// Fungsi pencarian
$search = '';
$search_condition = '';
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = $db->escape($_GET['search']);
    $search_condition = " AND (ps.no_order LIKE '%{$search}%' OR 
                           ps.client LIKE '%{$search}%' OR 
                           ps.part_number LIKE '%{$search}%' OR 
                           p.name LIKE '%{$search}%')";
}

// Query data jadwal produksi
$query = "SELECT ps.*, p.name AS product_name
          FROM production_schedule ps
          LEFT JOIN products p ON ps.part_number = p.part_number
          WHERE delivery_date BETWEEN '{$start_date}' AND '{$end_date}' {$search_condition}";
$result = $db->query($query);
$schedules = $result ? $db->while_loop($result) : [];

// Hitung total quantity
$total_quantity_query = "SELECT SUM(quantity_order) as total_quantity FROM production_schedule ps
                         LEFT JOIN products p ON ps.part_number = p.part_number
                         WHERE delivery_date BETWEEN '{$start_date}' AND '{$end_date}' {$search_condition}";
$total_quantity_result = $db->query($total_quantity_query);
$total_quantity = $total_quantity_result ? $db->fetch_assoc($total_quantity_result)['total_quantity'] : 0;

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">Jadwal Produksi - <?php echo date('F Y', strtotime($start_date)); ?></h3>
                </div>
                <div class="pull-right">
                    <a href="add_schedule.php" class="btn btn-primary">
                        <i class="glyphicon glyphicon-plus"></i> Tambah Jadwal Baru
                    </a>
                    <a href="production_schedule.php?action=delete_all&month=<?php echo date('Y-m', strtotime($start_date)); ?>" 
                       class="btn btn-danger" 
                       onclick="return confirm('Apakah Anda yakin ingin menghapus semua jadwal produksi untuk <?php echo date('F Y', strtotime($start_date)); ?>?');">
                        Hapus Semua
                    </a>
                </div>
            </div>
            <div class="panel-body">
                <form method="GET" action="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>
                    
                    <div class="form-group pull-right">
                        <div class="input-group">
                            <input type="text" class="form-control" name="search" placeholder="Cari..." value="<?php echo $search; ?>">
                            <span class="input-group-btn">
                                <button class="btn btn-default" type="submit">Cari</button>
                            </span>
                        </div>
                    </div>
                </form>
                <hr>

                <form action="production_schedule.php?month=<?php echo date('Y-m', strtotime($start_date)); ?>" method="POST" enctype="multipart/form-data" class="form-inline">
                    <div class="form-group">
                        <label for="excel_file">Upload File Excel:</label>
                        <input type="file" name="excel_file" id="excel_file" class="form-control" accept=".xlsx, .xls" required>
                    </div>
                    <button type="submit" name="upload_excel" class="btn btn-success">Import Excel</button>
                    <a href="templates/template_schedule.xlsx" class="btn btn-info" download>
                        Download Template
                    </a>
                </form>
                <hr>
                
                <div class="alert alert-info">
                    <strong>Total Quantity: </strong><?php echo number_format($total_quantity, 0); ?>
                    <?php if (!empty($search)): ?>
                        <span class="pull-right"><strong>Hasil pencarian: </strong><?php echo $search; ?></span>
                    <?php endif; ?>
                </div>

                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th class="text-center">#</th>
                                <th>Nomor Order</th>
                                <th>Klien</th>
                                <th>Part Number</th>
                                <th>Nama Produk</th>
                                <th class="text-center">Quantity</th>
                                <th class="text-center">Tanggal Pengiriman</th>
                                <th class="text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($schedules) > 0): ?>
                                <?php foreach ($schedules as $schedule) : ?>
                                    <tr>
                                        <td class="text-center"><?php echo count_id(); ?></td>
                                        <td><?php echo remove_junk($schedule['no_order']); ?></td>
                                        <td><?php echo remove_junk($schedule['client']); ?></td>
                                        <td><?php echo remove_junk($schedule['part_number']); ?></td>
                                        <td><?php echo remove_junk($schedule['product_name']); ?></td>
                                        <td class="text-center"><?php echo (int)$schedule['quantity_order']; ?></td>
                                        <td class="text-center"><?php echo date("d-m-Y", strtotime($schedule['delivery_date'])); ?></td>
                                        <td class="text-center">
                                            <div class="btn-group">
                                                <a href="edit_production_schedule.php?id=<?php echo (int)$schedule['id']; ?>" class="btn btn-info btn-xs" title="Edit">
                                                    <span class="glyphicon glyphicon-edit"></span>
                                                </a>
                                                <a href="delete_production_schedule.php?id=<?php echo (int)$schedule['id']; ?>" class="btn btn-danger btn-xs" title="Hapus" onclick="return confirm('Apakah Anda yakin ingin menghapus jadwal ini?');">
                                                    <span class="glyphicon glyphicon-trash"></span>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="8" class="text-center">Tidak ada jadwal produksi ditemukan.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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