<?php
$page_title = 'Tambah Akun COA';
require_once('includes/load.php');
page_require_level(5);

// =========================================================================
// Wajib: Sertakan library PhpSpreadsheet
// Pastikan path ini sesuai dengan struktur proyek Anda
// =========================================================================
require_once 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;

// =========================================================================
// Bagian untuk memproses formulir tambah COA manual
// =========================================================================
if (isset($_POST['add_coa'])) {
    $req_fields = array('coa-kode', 'coa-akun', 'coa-type');
    validate_fields($req_fields);

    if (empty($errors)) {
        $c_kode       = remove_junk($db->escape($_POST['coa-kode']));
        $c_akun       = remove_junk($db->escape($_POST['coa-akun']));
        $c_type_akun  = remove_junk($db->escape($_POST['coa-type']));

        // Check for existing kode
        $check_sql = "SELECT kode FROM coa WHERE kode = '{$c_kode}' LIMIT 1";
        $result = $db->query($check_sql);
        if ($db->num_rows($result) > 0) {
            $session->msg('d', 'Maaf, Kode COA sudah ada.');
            redirect('add_coa.php', false);
        }

        $sql  = "INSERT INTO coa (kode, akun, type_akun)";
        $sql .= " VALUES ('{$c_kode}', '{$c_akun}', '{$c_type_akun}')";

        if ($db->query($sql)) {
            $session->msg('s', "Akun COA berhasil ditambahkan.");
            redirect('coa.php', false);
        } else {
            $session->msg('d', 'Maaf, gagal menambahkan akun COA.');
            redirect('add_coa.php', false);
        }
    } else {
        $session->msg("d", $errors);
        redirect('add_coa.php', false);
    }
}

// =========================================================================
// Bagian untuk memproses impor file Excel
// =========================================================================
if (isset($_POST['import_coa']) && isset($_FILES['coa-file'])) {
    $file_name = $_FILES['coa-file']['name'];
    $file_tmp = $_FILES['coa-file']['tmp_name'];
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    // Validasi tipe file
    $allowed_ext = ['xlsx', 'xls'];
    if (!in_array($file_ext, $allowed_ext)) {
        $session->msg('d', 'Maaf, hanya file Excel (.xlsx atau .xls) yang diperbolehkan.');
        redirect('add_coa.php', false);
    }

    if (is_uploaded_file($file_tmp)) {
        $reader = null;
        if ($file_ext == 'xlsx') {
            $reader = new Xlsx();
        } else {
            $reader = new Xls();
        }
        
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($file_tmp);
        $worksheet = $spreadsheet->getActiveSheet();
        $highestRow = $worksheet->getHighestRow();

        $success_count = 0;
        $fail_count = 0;
        $total_rows = 0;

        // Loop dari baris ke-5, karena data dimulai dari baris tersebut (A1-D4 adalah header/kosong)
        for ($row = 5; $row <= $highestRow; $row++) {
            $total_rows++;
            $c_kode = $worksheet->getCell('A' . $row)->getValue();
            $c_akun = $worksheet->getCell('B' . $row)->getValue();
            $c_type_akun = $worksheet->getCell('C' . $row)->getValue();

            // Lewati baris jika data kosong
            if (empty($c_kode) && empty($c_akun) && empty($c_type_akun)) {
                continue;
            }

            // Periksa apakah kode COA sudah ada
            $check_sql = "SELECT kode FROM coa WHERE kode = '{$db->escape($c_kode)}' LIMIT 1";
            if ($db->num_rows($db->query($check_sql)) > 0) {
                $fail_count++;
                continue;
            }

            // Masukkan data ke database
            $sql  = "INSERT INTO coa (kode, akun, type_akun)";
            $sql .= " VALUES ('{$db->escape($c_kode)}', '{$db->escape($c_akun)}', '{$db->escape($c_type_akun)}')";

            if ($db->query($sql)) {
                $success_count++;
            } else {
                $fail_count++;
            }
        }

        $session->msg('s', "Impor selesai. Total baris data: {$total_rows}. Berhasil: {$success_count}. Gagal (kode duplikat): {$fail_count}.");
        redirect('coa.php', false);

    } else {
        $session->msg('d', 'Gagal mengunggah file.');
        redirect('add_coa.php', false);
    }
}
?>

<?php 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-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-th"></span>
                    <span>Tambah Akun COA Manual</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="add_coa.php" class="clearfix">
                    <div class="form-group">
                        <label for="coa-kode">Kode Akun</label>
                        <input type="text" class="form-control" name="coa-kode" placeholder="Misal: 1101" required>
                    </div>
                    <div class="form-group">
                        <label for="coa-akun">Nama Akun</label>
                        <input type="text" class="form-control" name="coa-akun" placeholder="Misal: Kas" required>
                    </div>
                    <div class="form-group">
                        <label for="coa-type">Tipe Akun</label>
                        <select class="form-control" name="coa-type" required>
                            <option value="">Pilih Tipe Akun</option>
                            <option value="Aktiva">Aktiva</option>
                            <option value="Kewajiban">Kewajiban</option>
                            <option value="Modal">Modal</option>
                            <option value="Pendapatan">Pendapatan</option>
                            <option value="Beban">Beban</option>
                            <option value="Beban Lain-lain">Beban Lain-lain</option>
                        </select>
                    </div>
                    <button type="submit" name="add_coa" class="btn btn-danger">Tambah Akun</button>
                </form>
            </div>
        </div>
    </div>
</div>

<hr>

<div class="row">
    <div class="col-md-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-upload"></span>
                    <span>Impor Akun COA dari Excel</span>
                </strong>
                <span class="pull-right">
                    <small>Struktur Excel: Kolom A: KODE, Kolom B: AKUN, Kolom C: TYPE AKUN</small>
                </span>
            </div>
            <div class="panel-body">
                <form action="add_coa.php" method="POST" enctype="multipart/form-data" class="clearfix">
                    <div class="form-group">
                        <label for="coa-file">Pilih File Excel</label>
                        <input type="file" name="coa-file" class="form-control-file" accept=".xlsx,.xls" required>
                        <small class="form-text text-muted">Pastikan file Anda dalam format **.xlsx** atau **.xls**.</small>
                    </div>
                    <button type="submit" name="import_coa" class="btn btn-success">Impor Data</button>
                </form>
            </div>
        </div>
    </div>
</div>

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