<?php
// api_coa.php
require_once 'auth_check.php';
require_once 'db.php';

header('Content-Type: application/json');
$action = $_GET['action'] ?? '';

try {
    // 1. Ambil Daftar Chart of Accounts
    if ($action === 'get_coas') {
        $stmt = $pdo->query("SELECT * FROM chart_of_accounts ORDER BY account_code ASC");
        echo json_encode(['status' => 'success', 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    }

    // 2. Simpan Akun Baru (Insert)
    elseif ($action === 'save_coa') {
        $account_code   = trim($_POST['account_code'] ?? '');
        $account_name   = trim($_POST['account_name'] ?? '');
        $account_type   = trim($_POST['account_type'] ?? '');
        $normal_balance = trim($_POST['normal_balance'] ?? '');

        if (empty($account_code) || empty($account_name) || empty($account_type) || empty($normal_balance)) {
            echo json_encode(['status' => 'error', 'message' => 'Semua field wajib diisi!']);
            exit;
        }

        // Cek apakah kode akun sudah ada
        $stmtCheck = $pdo->prepare("SELECT COUNT(*) AS total FROM chart_of_accounts WHERE account_code = ?");
        $stmtCheck->execute([$account_code]);
        if ($stmtCheck->fetch()['total'] > 0) {
            echo json_encode(['status' => 'error', 'message' => "Kode Akun '$account_code' sudah terdaftar!"]);
            exit;
        }

        $stmtIns = $pdo->prepare("INSERT INTO chart_of_accounts (account_code, account_name, account_type, normal_balance) VALUES (?, ?, ?, ?)");
        $stmtIns->execute([$account_code, $account_name, $account_type, $normal_balance]);

        echo json_encode(['status' => 'success', 'message' => 'Akun berhasil ditambahkan!']);
    }

    // 3. Update Akun (Edit)
    elseif ($action === 'update_coa') {
        $old_code       = trim($_POST['old_code'] ?? '');
        $account_code   = trim($_POST['account_code'] ?? '');
        $account_name   = trim($_POST['account_name'] ?? '');
        $account_type   = trim($_POST['account_type'] ?? '');
        $normal_balance = trim($_POST['normal_balance'] ?? '');
        $is_active      = intval($_POST['is_active'] ?? 1);

        if (empty($old_code) || empty($account_code) || empty($account_name)) {
            echo json_encode(['status' => 'error', 'message' => 'Data tidak lengkap!']);
            exit;
        }

        // SYARAT 1: Cek apakah akun sudah digunakan di tabel journal_details
        $stmtUsed = $pdo->prepare("SELECT COUNT(*) AS total FROM journal_details WHERE account_code = ?");
        $stmtUsed->execute([$old_code]);
        $isUsed = $stmtUsed->fetch()['total'] > 0;

        // Jika sudah digunakan, kode akun tidak boleh diubah untuk menjaga integritas transaksi masa lalu
        if ($isUsed && $old_code !== $account_code) {
            echo json_encode(['status' => 'error', 'message' => 'Akun ini sudah memiliki riwayat transaksi di jurnal. Kode akun tidak dapat diubah!']);
            exit;
        }

        $stmtUpd = $pdo->prepare("UPDATE chart_of_accounts SET account_code = ?, account_name = ?, account_type = ?, normal_balance = ?, is_active = ? WHERE account_code = ?");
        $stmtUpd->execute([$account_code, $account_name, $account_type, $normal_balance, $is_active, $old_code]);

        echo json_encode(['status' => 'success', 'message' => 'Data akun berhasil diperbarui!']);
    }

    // 4. Hapus Akun (Delete) dengan Syarat Relasi Jurnal
    elseif ($action === 'delete_coa') {
        $account_code = trim($_POST['account_code'] ?? '');

        if (empty($account_code)) {
            echo json_encode(['status' => 'error', 'message' => 'Kode akun tidak valid!']);
            exit;
        }

        // SYARAT 2: Cek apakah ada data di tabel journal_details
        $stmtCheck = $pdo->prepare("SELECT COUNT(*) AS total FROM journal_details WHERE account_code = ?");
        $stmtCheck->execute([$account_code]);
        $usedCount = $stmtCheck->fetch()['total'];

        if ($usedCount > 0) {
            echo json_encode(['status' => 'error', 'message' => "Akun [$account_code] tidak dapat dihapus karena sudah digunakan dalam $usedCount transaksi jurnal!"]);
            exit;
        }

        $stmtDel = $pdo->prepare("DELETE FROM chart_of_accounts WHERE account_code = ?");
        $stmtDel->execute([$account_code]);

        echo json_encode(['status' => 'success', 'message' => "Akun [$account_code] berhasil dihapus."]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Aksi tidak valid!']);
    }

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Error: ' . $e->getMessage()]);
}
?>