<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

require 'config.php'; 

if ($conn->connect_error) {
    echo json_encode(['success' => false, 'error' => 'Koneksi DB Gagal: ' . $conn->connect_error]);
    exit();
}

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'load':
        handle_load($conn);
        break;
    case 'save':
        handle_save($conn);
        break;
    case 'delete':
        handle_delete($conn);
        break;
    case 'get_cash_accounts':
        get_cash_accounts($conn);
        break;
    case 'get_all_coa':
        get_all_coa($conn);
        break;
    default:
        echo json_encode(['success' => false, 'error' => 'Aksi tidak valid.']);
        break;
}

$conn->close();

// =====================================================================
// FUNGSI-FUNGSI HANDLER
// =====================================================================

function handle_load($conn) {
    $account = $_POST['account'] ?? '';
    $period = $_POST['period'] ?? '';

    if (empty($account) || empty($period)) {
        echo json_encode(['success' => false, 'error' => 'Akun dan Periode harus diisi.']);
        return;
    }

    $year = substr($period, 0, 4);
    $month = substr($period, 4, 2);
    $first_day_of_month = "$year-$month-01";
    
    $opening_balance = 0;
    $stmt_ob = $conn->prepare("SELECT SUM(debet) - SUM(kredit) as opening_balance FROM ajurnal WHERE account = ? AND tanggal < ?");
    if($stmt_ob) {
        $stmt_ob->bind_param("ss", $account, $first_day_of_month);
        $stmt_ob->execute();
        $result_ob = $stmt_ob->get_result();
        $row_ob = $result_ob->fetch_assoc();
        $opening_balance = $row_ob['opening_balance'] ?? 0;
        $stmt_ob->close();
    }

    $account_name = '';
    $stmt_name = $conn->prepare("SELECT nm_akun FROM coa WHERE kd_akun = ?");
    if($stmt_name) {
        $stmt_name->bind_param("s", $account);
        $stmt_name->execute();
        $result_name = $stmt_name->get_result();
        $row_name = $result_name->fetch_assoc();
        $account_name = $row_name['nm_akun'] ?? '';
        $stmt_name->close();
    }
    
    
    $stmt = $conn->prepare("SELECT * FROM ajurnal WHERE account = ? AND DATE_FORMAT(tanggal, '%Y%m') = ? ORDER BY id ASC");
    if (!$stmt) {
        echo json_encode(['success' => false, 'error' => 'Prepare statement gagal: ' . $conn->error]);
        return;
    }

    $stmt->bind_param("ss", $account, $period);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = [];
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    $stmt->close();

    echo json_encode([
        'success' => true, 
        'data' => $data,
        'opening_balance' => $opening_balance,
        'account_name' => $account_name
    ]);
}


function handle_save($conn) {
    $data = $_POST['data'] ?? null;
    if (!$data) {
        echo json_encode(['success' => false, 'error' => 'Tidak ada data.']);
        return;
    }

    $id = $data['id'] ?? null;
    // $tanggal = !empty($data['tanggal']) ? $data['tanggal'] : date('Y-m-d');
        $tanggal_input = $data['tanggal'] ?? '';
    if (!empty($tanggal_input)) {
        // Buat objek DateTime dari format 'dd-mm-yyyy'
        $date_obj = DateTime::createFromFormat('d-m-Y', $tanggal_input);
        if ($date_obj) {
            // Jika berhasil, format ulang ke format SQL 'YYYY-MM-DD'
            $tanggal = $date_obj->format('Y-m-d');
        } else {
            // Jika format dari user salah, default ke hari ini untuk mencegah error
            $tanggal = date('Y-m-d'); 
        }
    } else {
        // Jika user tidak mengisi tanggal, default ke hari ini
        $tanggal = date('Y-m-d');
    };
    // --
    $main_account = $data['main_account'] ?? '';
    $nama_acc = $data['nama_acc'] ?? ''; // <-- AMBIL DATA NAMA AKUN BARU
    $lawan = $data['lawan'] ?? '';
    $nama_lawan = $data['nama_lawan'] ?? '';
    $ket = $data['ket'] ?? '';
    $debet = (float)str_replace(',', '', $data['debet'] ?? 0);
    $kredit = (float)str_replace(',', '', $data['kredit'] ?? 0);
    $reff = $data['reff'] ?? ''; 
    $master = $data['master'] ?? 0;

    if (empty($main_account) || empty($lawan) || empty($tanggal)) {
        echo json_encode(['success' => false, 'error' => 'Data tidak lengkap.']);
        return;
    }

    if (!empty($id)) {
        // --- PROSES UPDATE ---
        $nomor = $data['nomor'] ?? '';
        // Ubah Panggilan SP untuk UPDATE
        $stmt = $conn->prepare("CALL sp_update_ajurnal(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); // 12 parameter
        if (!$stmt) {
             echo json_encode(['success' => false, 'error' => 'SP Update Prepare Gagal: ' . $conn->error]); return;
        }
        // Sesuaikan bind_param
        $stmt->bind_param("isssisddssss", $id, $tanggal, $nomor, $main_account, $nama_acc, $master, $debet, $kredit, $lawan, $nama_lawan, $reff, $ket);
    } 
    else {
        // --- PROSES INSERT ---

        // (Logika penomoran Anda sudah bagus, tidak perlu diubah)
        $year_2_digit = date('y', strtotime($tanggal));
        $prefix = "JE1" . $year_2_digit;
        $like_pattern = $prefix . '%';
        $sql_get_last_num = "SELECT MAX(CAST(SUBSTRING(nomor, 6) AS UNSIGNED)) as last_num FROM ajurnal WHERE nomor LIKE ?";
        $stmt_num = $conn->prepare($sql_get_last_num);
        $stmt_num->bind_param("s", $like_pattern);
        $stmt_num->execute();
        $result_num = $stmt_num->get_result()->fetch_assoc();
        $stmt_num->close();
        $last_num = $result_num['last_num'] ?? 0;
        $next_num = $last_num + 1;
        $nomor = $prefix . str_pad($next_num, 5, '0', STR_PAD_LEFT);
        
        // Ubah Panggilan SP untuk INSERT
        $stmt = $conn->prepare("CALL sp_insert_ajurnal(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); // 11 parameter
        if (!$stmt) {
             echo json_encode(['success' => false, 'error' => 'SP Insert Prepare Gagal: ' . $conn->error]); return;
        }
        // Sesuaikan bind_param
        $stmt->bind_param("ssssidddsss", $tanggal, $nomor, $main_account, $nama_acc, $master, $debet, $kredit, $lawan, $nama_lawan, $reff, $ket);
    }

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Data berhasil disimpan.']);
    } else {
        echo json_encode(['success' => false, 'error' => 'Eksekusi SP Gagal: ' . $stmt->error]);
    }
    $stmt->close();
}


function handle_delete($conn) {
    $nomor = $_POST['nomor'] ?? '';
    if (empty($nomor)) {
        echo json_encode(['success' => false, 'error' => 'Nomor transaksi tidak ada.']);
        return;
    }
    $stmt = $conn->prepare("DELETE FROM ajurnal WHERE nomor = ?");
     if ($stmt === false) {
        echo json_encode(['success' => false, 'error' => 'Prepare delete gagal: ' . $conn->error]);
        return;
    }
    $stmt->bind_param("s", $nomor);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Transaksi berhasil dihapus.']);
    } else {
        echo json_encode(['success' => false, 'error' => 'Gagal menghapus: ' . $stmt->error]);
    }
    $stmt->close();
}

function get_cash_accounts($conn) {
    $sql = "SELECT kd_akun, nm_akun FROM coa WHERE kd_akun >= '1111' AND kd_akun <= '11129' ORDER BY kd_akun";
    $result = $conn->query($sql);
    $data = [];
    if ($result) {
        while($row = $result->fetch_assoc()) {
            
            $data[] = $row;
        }
        echo json_encode(['success' => true, 'data' => $data]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Query gagal: ' . $conn->error]);
    }
}

function get_all_coa($conn) {
    $sql = "SELECT kd_akun, nm_akun FROM coa ORDER BY kd_akun";
    $result = $conn->query($sql);
    $data = [];
    if ($result) {
        while($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        echo json_encode(['success' => true, 'data' => $data]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Query COA gagal: ' . $conn->error]);
    }
}
?>
