<?php
session_start();
require_once __DIR__ . '/config/config.php';

if (!isset($_SESSION['login']) || $_SESSION['role'] !== 'admin') {
    die("Akses ditolak");
}

$pesan = '';

/* ================= TAMBAH MANUAL ================= */
if (isset($_POST['simpan'])) {

    $kode  = trim($_POST['kode_rekening']);
    $nama  = trim($_POST['nama_rekening']);
    $kel   = trim($_POST['kelompok']);
    $jenis = trim($_POST['jenis_belanja']);

    if ($kode=='' || $nama=='' || $kel=='' || $jenis=='') {
        $pesan = "❌ Semua field wajib diisi";
    } else {

        $cek = $conn->prepare("SELECT 1 FROM rekening_map WHERE kode_rekening=?");
        $cek->bind_param("s", $kode);
        $cek->execute();
        $cek->store_result();

        if ($cek->num_rows > 0) {
            $pesan = "❌ Kode rekening sudah ada";
        } else {

            $ins = $conn->prepare("
                INSERT INTO rekening_map
                (kode_rekening, nama_rekening, kelompok, jenis_belanja)
                VALUES (?, ?, ?, ?)
            ");
            $ins->bind_param("ssss", $kode, $nama, $kel, $jenis);
            $ins->execute();

            header("Location: list_rekening_map.php?msg=tambah");
            exit;
        }
    }
}

/* ================= IMPORT CSV ================= */
if (isset($_POST['import'])) {

    if (!isset($_FILES['file_csv']) || $_FILES['file_csv']['error'] !== UPLOAD_ERR_OK) {
        $pesan = "❌ File CSV belum dipilih";
    } else {

        $file = fopen($_FILES['file_csv']['tmp_name'], "r");

        // DETEKSI DELIMITER
        $sample = fgets($file);
        rewind($file);
        $delimiter = (substr_count($sample, ';') > substr_count($sample, ',')) ? ';' : ',';

        // SKIP HEADER
        fgetcsv($file, 1000, $delimiter);

        $jumlah = 0;

        while (($row = fgetcsv($file, 1000, $delimiter)) !== false) {

            if (count($row) < 4) continue;

            $kode  = trim($row[0]);
            $nama  = trim($row[1]);
            $kel   = trim($row[2]);
            $jenis = trim($row[3]);

            if ($kode == '') continue;

            $cek = $conn->prepare("SELECT 1 FROM rekening_map WHERE kode_rekening=?");
            $cek->bind_param("s", $kode);
            $cek->execute();
            $cek->store_result();

            if ($cek->num_rows == 0) {
                $ins = $conn->prepare("
                    INSERT INTO rekening_map
                    (kode_rekening, nama_rekening, kelompok, jenis_belanja)
                    VALUES (?, ?, ?, ?)
                ");
                $ins->bind_param("ssss", $kode, $nama, $kel, $jenis);
                $ins->execute();
                $jumlah++;
            }
        }

        fclose($file);

        header("Location: list_rekening_map.php?msg=import&jml=$jumlah");
        exit;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Rekening Map - Admin</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-light">

<div class="container mt-4">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="mb-0">📘 Kelola Rekening Map</h4>
        <a href="list_rekening_map.php" class="btn btn-secondary">📋 Lihat Daftar</a>
    </div>

    <?php if($pesan!=''): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($pesan) ?></div>
    <?php endif; ?>

    <div class="row g-4">

        <!-- TAMBAH MANUAL -->
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    ➕ Tambah Rekening Manual
                </div>
                <div class="card-body">
                    <form method="post">
                        <div class="mb-2">
                            <label>Kode Rekening</label>
                            <input class="form-control" name="kode_rekening" required>
                        </div>
                        <div class="mb-2">
                            <label>Nama Rekening</label>
                            <input class="form-control" name="nama_rekening" required>
                        </div>
                        <div class="mb-2">
                            <label>Kelompok</label>
                            <select class="form-select" name="kelompok" required>
                                <option value="">-- pilih --</option>
                                <option>BHP</option>
                                <option>BJJ</option>
                                <option>BMM</option>
                                <option>BMAL</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label>Jenis Belanja</label>
                            <input class="form-control" name="jenis_belanja" value="Barang Habis Pakai" required>
                        </div>
                        <button class="btn btn-success w-100" name="simpan">💾 Simpan</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- IMPORT -->
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-header bg-warning">
                    📥 Import CSV
                </div>
                <div class="card-body">
                    <form method="post" enctype="multipart/form-data">
                        <input type="file" class="form-control mb-2" name="file_csv" accept=".csv" required>
                        <button class="btn btn-warning w-100" name="import">Import Data</button>
                    </form>
                    <small class="text-muted d-block mt-2">
                        Format: kode_rekening | nama_rekening | kelompok | jenis_belanja
                    </small>
                </div>
            </div>
        
			<div class="card shadow-sm"> 
			<div class="card-header bg-success text-white"> 📤 Export Data </div> 
			<div class="card-body text-center"> 
			<a href="?export=1" class="btn btn-success w-100"> Download CSV </a> 
			</div> 
		</div> 
    </div>
</div>

</div>
</body>
</html>
