ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

<?php
// Pastikan tidak ada spasi atau karakter di sini sebelum <?php
require 'vendor/autoload.php'; // Load Composer autoloader
use PhpOffice\PhpSpreadsheet\IOFactory;

$page_title = 'Recorded Production Outputs';
require_once('includes/load.php'); // Pastikan session_start() ada di dalam file ini dan dipanggil paling awal.
page_require_level(3); // Pastikan user level cukup

// --- AKTIFKAN TAMPILAN ERROR (HANYA UNTUK DEVELOPMENT!) ---
// JANGAN BIARKAN INI AKTIF DI PRODUCTION SERVER!
ini_set('display_errors', 1); // <-- UNCOMMENT THIS
ini_set('display_startup_errors', 1); // <-- UNCOMMENT THIS
error_reporting(E_ALL); // <-- UNCOMMENT THIS

// Ambil pesan dari session jika ada, lalu hapus dari session
$msg = null;
if (isset($_SESSION['msg'])) {
    $msg = $_SESSION['msg'];
    unset($_SESSION['msg']); // Penting: hapus pesan setelah diambil
}

// Inisialisasi variabel error
$errors = [];

// --- Logika Penanganan Delete ---
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];

    $output_to_delete = find_by_id('output_schedule', $delete_id);
    if (!$output_to_delete) {
        $_SESSION['msg'] = create_msg("Record untuk dihapus tidak ditemukan.", "danger");
        redirect('recorded_outputs.php'); // No need for 'true' if redirect() defaults to exit
    }

    $delete_result = delete_by_id('output_schedule', $delete_id);

    if ($delete_result) {
        $_SESSION['msg'] = create_msg("Output produksi berhasil dihapus.", "success");
        redirect('recorded_outputs.php'); // This should now exit the script
    } else {
        $_SESSION['msg'] = create_msg("Gagal menghapus output produksi.", "danger");
        redirect('recorded_outputs.php'); // This should now exit the script
    }
}

// --- Logika Penanganan Edit (Menampilkan Form dan Memproses Update) ---
$edit_output = null;
$is_editing = false;

if (isset($_GET['edit_id'])) {
    $is_editing = true;
    $edit_id = (int)$_GET['edit_id'];

    $query_edit_output = "
        SELECT
            os.*,
            ps.no_order,
            ps.part_number,
            p.name AS product_name
        FROM
            output_schedule os
        JOIN
            production_schedule ps ON os.schedule_id = ps.id
        LEFT JOIN
            products p ON ps.part_number = p.part_number
        WHERE
            os.id = '{$edit_id}'
        LIMIT 1
    ";
    $result_edit_output = $db->query($query_edit_output);
    $edit_output = $result_edit_output ? $db->fetch_assoc($result_edit_output) : null;

    if (!$edit_output) {
        $_SESSION['msg'] = create_msg("Record output untuk diedit tidak ditemukan.", "danger");
        $is_editing = false; // Reset flag
        redirect('recorded_outputs.php'); // Redirect and exit
    }
}

// Jika form update disubmit (tombol 'update_output' diklik)
if (isset($_POST['update_output'])) {
    $edit_id_post = (int)$_POST['output_id'];
    $req_fields = array('output_quantity', 'output_date');
    validate_fields($req_fields);

    if (empty($errors)) {
        $output_quantity = $db->escape($_POST['output_quantity']);
        $output_date = $db->escape($_POST['output_date']);

        $sql = "UPDATE output_schedule SET ";
        $sql .= "output_quantity = '{$output_quantity}', ";
        $sql .= "output_date = '{$output_date}' ";
        $sql .= "WHERE id = '{$edit_id_post}'";

        $result = $db->query($sql);

        if ($result && $db->affected_rows() === 1) {
            $_SESSION['msg'] = create_msg("Output produksi berhasil diperbarui.", "success");
            redirect('recorded_outputs.php'); // Redirect and exit
        } else {
            $_SESSION['msg'] = create_msg("Gagal memperbarui output produksi. Mungkin tidak ada perubahan?", "warning");
            redirect('recorded_outputs.php?edit_id=' . $edit_id_post); // Redirect and exit
        }
    } else {
        $_SESSION['msg'] = create_msg($errors, "danger");
        redirect('recorded_outputs.php?edit_id=' . $edit_id_post); // Redirect and exit
    }
}

// --- Logika Filter dan Pencarian ---
$selected_month = isset($_GET['month']) ? $_GET['month'] : date('Y-m');
$start_date = $selected_month . '-01';
$end_date = date("Y-m-t", strtotime($start_date));

$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 untuk Semua Output Produksi yang Tercatat ---
$query_outputs = "
    SELECT
        os.*,
        ps.no_order,
        ps.part_number,
        ps.quantity_order AS scheduled_quantity,
        p.name AS product_name
    FROM
        output_schedule os
    JOIN
        production_schedule ps ON os.schedule_id = ps.id
    LEFT JOIN
        products p ON ps.part_number = p.part_number
    WHERE
        os.output_date BETWEEN '{$start_date}' AND '{$end_date}'
        {$search_condition}
    ORDER BY
        os.output_date DESC, os.created_at DESC
";
$result_outputs = $db->query($query_outputs);
$recorded_outputs = $result_outputs ? $db->while_loop($result_outputs) : [];

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

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

<?php if ($is_editing && $edit_output): ?>
<div class="row">
    <div class="col-md-8">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <div class="pull-left">
                    <h3 class="panel-title">Edit Output Produksi (ID: <?php echo (int)$edit_output['id']; ?>)</h3>
                </div>
                <div class="pull-right">
                    <a href="recorded_outputs.php" class="btn btn-primary">
                        <span class="glyphicon glyphicon-remove"></span> Batalkan Edit
                    </a>
                </div>
            </div>
            <div class="panel-body">
                <form method="post" action="recorded_outputs.php">
                    <input type="hidden" name="output_id" value="<?php echo (int)$edit_output['id']; ?>">
                    <div class="form-group">
                        <label for="no_order">Nomor Order</label>
                        <input type="text" class="form-control" value="<?php echo remove_junk($edit_output['no_order']); ?>" disabled>
                    </div>
                    <div class="form-group">
                        <label for="part_number">Nomor Bagian</label>
                        <input type="text" class="form-control" value="<?php echo remove_junk($edit_output['part_number']); ?>" disabled>
                    </div>
                    <div class="form-group">
                        <label for="product_name">Nama Produk</label>
                        <input type="text" class="form-control" value="<?php echo remove_junk($edit_output['product_name']); ?>" disabled>
                    </div>
                    <div class="form-group">
                        <label for="output_quantity">Jumlah Output</label>
                        <input type="number" class="form-control" name="output_quantity" value="<?php echo (int)$edit_output['output_quantity']; ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="output_date">Tanggal Output</label>
                        <input type="date" class="form-control" name="output_date" value="<?php echo htmlspecialchars($edit_output['output_date']); ?>" required>
                    </div>
                    <button type="submit" name="update_output" class="btn btn-success">Perbarui Output</button>
                </form>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<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">Output Produksi yang Tercatat - <?php echo date('F Y', strtotime($start_date)); ?></h3>
                </div>
                <div class="pull-right">
                    <a href="production_output_schedule.php" class="btn btn-primary">
                        <span class="glyphicon glyphicon-arrow-left"></span> Kembali ke Jadwal Produksi
                    </a>
                </div>
            </div>
            <div class="panel-body">
                <form method="GET" action="recorded_outputs.php" class="form-inline mb-3">
                    <div class="form-group">
                        <label for="month">Pilih Bulan:</label>
                        <input type="month" name="month" id="month" class="form-control" value="<?php echo htmlspecialchars($selected_month); ?>">
                    </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 htmlspecialchars($search); ?>">
                            <span class="input-group-btn">
                                <button class="btn btn-default" type="submit">Cari</button>
                            </span>
                        </div>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th class="text-center">#</th>
                                <th>Nomor Order</th>
                                <th>Nomor Bagian</th>
                                <th>Nama Produk</th>
                                <th class="text-center">Jumlah Output</th>
                                <th class="text-center">Tanggal Output</th>
                                <th class="text-center">Dicatat Pada</th>
                                <th class="text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($recorded_outputs) > 0): ?>
                                <?php foreach ($recorded_outputs as $output) : ?>
                                    <tr>
                                        <td class="text-center"><?php echo count_id(); ?></td>
                                        <td><?php echo remove_junk($output['no_order']); ?></td>
                                        <td><?php echo remove_junk($output['part_number']); ?></td>
                                        <td><?php echo remove_junk($output['product_name']); ?></td>
                                        <td class="text-center"><?php echo (int)$output['output_quantity']; ?></td>
                                        <td class="text-center"><?php echo date("d-m-Y", strtotime($output['output_date'])); ?></td>
                                        <td class="text-center"><?php echo read_date($output['created_at']); ?></td>
                                        <td class="text-center">
                                            <div class="btn-group">
                                                <a href="recorded_outputs.php?edit_id=<?php echo (int)$output['id']; ?>" class="btn btn-warning btn-xs" title="Edit" data-toggle="tooltip">
                                                    <span class="glyphicon glyphicon-edit"></span>
                                                </a>
                                                <a href="recorded_outputs.php?delete_id=<?php echo (int)$output['id']; ?>" class="btn btn-danger btn-xs" title="Hapus" data-toggle="tooltip" onclick="return confirm('Anda yakin ingin menghapus record ini?');">
                                                    <span class="glyphicon glyphicon-trash"></span>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="8" class="text-center">Tidak ada output produksi yang tercatat untuk kriteria yang dipilih.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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