<?php
// api_payment.php
require_once 'auth_check.php';
require_once 'db.php';

header('Content-Type: application/json');
$action = $_GET['action'] ?? '';

try {
    // 1. Ambil daftar Invoice yang statusnya 'Unpaid' atau 'Partial'
    if ($action === 'get_unpaid_invoices') {
        $stmt = $pdo->query("
            SELECT inv.id, inv.invoice_number, inv.invoice_date, inv.grand_total, c.customer_name 
            FROM invoices inv 
            JOIN delivery_orders do ON inv.do_id = do.id 
            JOIN sales_orders so ON do.so_id = so.id 
            JOIN customers c ON so.customer_id = c.id 
            WHERE inv.status IN ('Unpaid', 'Partial') 
            ORDER BY inv.id DESC
        ");
        echo json_encode(['status' => 'success', 'data' => $stmt->fetchAll()]);
    }

    // 2. Ambil detail sisa tagihan berdasarkan invoice_id
    elseif ($action === 'get_invoice_detail') {
        $invoice_id = $_GET['invoice_id'] ?? 0;
        $stmt = $pdo->prepare("
            SELECT inv.*, c.customer_name 
            FROM invoices inv 
            JOIN delivery_orders do ON inv.do_id = do.id 
            JOIN sales_orders so ON do.so_id = so.id 
            JOIN customers c ON so.customer_id = c.id 
            WHERE inv.id = ?
        ");
        $stmt->execute([$invoice_id]);
        $invoice = $stmt->fetch();

        if ($invoice) {
            echo json_encode(['status' => 'success', 'invoice' => $invoice]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Invoice tidak ditemukan']);
        }
    }

    // 3. Simpan Pembayaran & Auto-Journal (Debit: 1100 Kas/Bank, Kredit: 1120 Piutang Usaha)
    // 3. Simpan Pembayaran dengan Dukungan Partial Payment
    elseif ($action === 'save_payment') {
        $invoice_id     = $_POST['invoice_id'] ?? '';
        $payment_date   = $_POST['payment_date'] ?? date('Y-m-d');
        $amount         = floatval($_POST['amount'] ?? 0);
        $payment_method = $_POST['payment_method'] ?? 'Transfer Bank';
        $notes          = $_POST['notes'] ?? '';

        if (empty($invoice_id) || $amount <= 0) {
            echo json_encode(['status' => 'error', 'message' => 'Invoice dan jumlah pembayaran wajib diisi dengan benar!']);
            exit;
        }

        // Ambil data invoice & pelanggan
        $stmtInv = $pdo->prepare("
            SELECT inv.*, c.customer_name 
            FROM invoices inv 
            JOIN delivery_orders do ON inv.do_id = do.id 
            JOIN sales_orders so ON do.so_id = so.id 
            JOIN customers c ON so.customer_id = c.id 
            WHERE inv.id = ?
        ");
        $stmtInv->execute([$invoice_id]);
        $inv = $stmtInv->fetch();

        if (!$inv) {
            echo json_encode(['status' => 'error', 'message' => 'Invoice tidak ditemukan!']);
            exit;
        }

        // Hitung total pembayaran yang sudah pernah masuk sebelumnya untuk invoice ini
        $stmtTotalPay = $pdo->prepare("SELECT SUM(amount) AS total_paid FROM payments WHERE invoice_id = ?");
        $stmtTotalPay->execute([$invoice_id]);
        $already_paid = floatval($stmtTotalPay->fetch()['total_paid'] ?? 0);

        $grand_total = floatval($inv['grand_total']);
        $sisa_piutang = $grand_total - $already_paid;

        if ($amount > $sisa_piutang) {
            echo json_encode(['status' => 'error', 'message' => 'Jumlah bayar melebihi sisa tagihan/piutang yang tersisa!']);
            exit;
        }

        $customer_name  = $inv['customer_name'];
        $invoice_number = $inv['invoice_number'];

        // Tentukan status invoice baru (Paid jika lunas, Partial jika masih kurang)
        $new_status = (($already_paid + $amount) >= $grand_total) ? 'Paid' : 'Partial';

        // Generate Nomor Pembayaran Otomatis (Format: PAY-YYYYMM-XXXX)
        $prefix = "PAY-" . date('Ym') . "-";
        $stmtSeq = $pdo->query("SELECT COUNT(*) AS total FROM payments WHERE payment_number LIKE '$prefix%'");
        $seq = $stmtSeq->fetch()['total'] + 1;
        $payment_number = $prefix . str_pad($seq, 4, '0', STR_PAD_LEFT);

        $pdo->beginTransaction();

        // A. Simpan Header Pembayaran
        $stmtPay = $pdo->prepare("INSERT INTO payments (payment_number, invoice_id, payment_date, amount, payment_method, notes) VALUES (?, ?, ?, ?, ?, ?)");
        $stmtPay->execute([$payment_number, $invoice_id, $payment_date, $amount, $payment_method, $notes]);
        $payment_id = $pdo->lastInsertId();

        // B. Update Status Invoice (Paid / Partial)
        $stmtUpdateInv = $pdo->prepare("UPDATE invoices SET status = ? WHERE id = ?");
        $stmtUpdateInv->execute([$new_status, $invoice_id]);

        // C. LOGIKA AUTO-JOURNAL PEMBAYARAN SEBAGIAN
        $jrnPrefix = "JRN-" . date('Ym') . "-";
        $stmtJrnSeq = $pdo->query("SELECT COUNT(*) AS total FROM journal_entries WHERE journal_number LIKE '$jrnPrefix%'");
        $jrnSeq = $stmtJrnSeq->fetch()['total'] + 1;
        $journal_number = $jrnPrefix . str_pad($jrnSeq, 4, '0', STR_PAD_LEFT);

        $description = "Penerimaan Pembayaran Sebagian/Piutang a/n $customer_name (Inv: $invoice_number, Pay: $payment_number)";

        // 1. Insert Header Jurnal
        $stmtJrnHeader = $pdo->prepare("INSERT INTO journal_entries (journal_number, journal_date, reference_type, reference_id, description, total_debit, total_credit) VALUES (?, ?, 'Payment', ?, ?, ?, ?)");
        $stmtJrnHeader->execute([$journal_number, $payment_date, $payment_id, $description, $amount, $amount]);
        $journal_id = $pdo->lastInsertId();

        // 2. Debit Kas/Bank (1100) sebesar yang dibayar
        $stmtJrnDetail = $pdo->prepare("INSERT INTO journal_details (journal_id, account_code, debit, credit) VALUES (?, ?, ?, ?)");
        $stmtJrnDetail->execute([$journal_id, '1100', $amount, 0.00]);

        // 3. Kredit Piutang Usaha (1120) sebesar yang dibayar
        $stmtJrnDetail->execute([$journal_id, '1120', 0.00, $amount]);

        $pdo->commit();
        echo json_encode([
            'status' => 'success', 
            'message' => "Pembayaran sebesar Rp " . number_format($amount, 0, ',', '.') . " berhasil dicatat! Status Invoice: $new_status"
        ]);
    }

    // 4. Ambil Daftar Riwayat Pembayaran (List View)
    elseif ($action === 'get_payment_list') {
        $stmt = $pdo->query("
            SELECT p.*, inv.invoice_number, c.customer_name 
            FROM payments p 
            JOIN invoices inv ON p.invoice_id = inv.id 
            JOIN delivery_orders do ON inv.do_id = do.id 
            JOIN sales_orders so ON do.so_id = so.id 
            JOIN customers c ON so.customer_id = c.id 
            ORDER BY p.id DESC
        ");
        echo json_encode(['status' => 'success', 'data' => $stmt->fetchAll()]);
    }

    // 5. Hapus Pembayaran & Jurnal Terkait
    elseif ($action === 'delete_payment') {
        $id = $_POST['id'] ?? '';
        if (empty($id)) {
            echo json_encode(['status' => 'error', 'message' => 'ID Pembayaran tidak valid!']);
            exit;
        }

        try {
            $pdo->beginTransaction();

            // Ambil invoice_id terkait sebelum pembayaran dihapus
            $stmtGetPay = $pdo->prepare("SELECT invoice_id FROM payments WHERE id = ?");
            $stmtGetPay->execute([$id]);
            $payData = $stmtGetPay->fetch();
            $invoice_id = $payData['invoice_id'] ?? null;

            // Hapus Jurnal Terkait
            $stmtGetJrn = $pdo->prepare("SELECT id FROM journal_entries WHERE reference_type = 'Payment' AND reference_id = ?");
            $stmtGetJrn->execute([$id]);
            $journal = $stmtGetJrn->fetch();

            if ($journal) {
                $journal_id = $journal['id'];
                $pdo->prepare("DELETE FROM journal_details WHERE journal_id = ?")->execute([$journal_id]);
                $pdo->prepare("DELETE FROM journal_entries WHERE id = ?")->execute([$journal_id]);
            }

            // Kembalikan status invoice menjadi 'Unpaid'
            if ($invoice_id) {
                $pdo->prepare("UPDATE invoices SET status = 'Unpaid' WHERE id = ?")->execute([$invoice_id]);
            }

            // Hapus Pembayaran
            $pdo->prepare("DELETE FROM payments WHERE id = ?")->execute([$id]);

            $pdo->commit();
            echo json_encode(['status' => 'success', 'message' => 'Data pembayaran berhasil dihapus dan status invoice dikembalikan!']);
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['status' => 'error', 'message' => 'Gagal menghapus pembayaran: ' . $e->getMessage()]);
        }
    }
	
	//6. Ambil Detail Auto-Journal berdasarkan Payment ID
    elseif ($action === 'get_payment_journal') {
        $payment_id = $_GET['payment_id'] ?? 0;

        // Ambil Header Jurnal
        $stmtJrn = $pdo->prepare("
            SELECT * FROM journal_entries 
            WHERE reference_type = 'Payment' AND reference_id = ?
        ");
        $stmtJrn->execute([$payment_id]);
        $journal = $stmtJrn->fetch();

        if ($journal) {
            // Ambil Detail Jurnal (Debit & Kredit)
            $stmtDetail = $pdo->prepare("
                SELECT jd.*, 
                       CASE 
                           WHEN jd.account_code = '1100' THEN 'Kas / Bank'
                           WHEN jd.account_code = '1120' THEN 'Piutang Usaha'
                           WHEN jd.account_code = '4100' THEN 'Penjualan Barang'
                           ELSE 'Akun Lainnya'
                       END AS account_name
                FROM journal_details jd 
                WHERE jd.journal_id = ?
                ORDER BY jd.id ASC
            ");
            $stmtDetail->execute([$journal['id']]);
            $details = $stmtDetail->fetchAll();

            echo json_encode([
                'status' => 'success',
                'journal' => $journal,
                'details' => $details
            ]);
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => 'Jurnal akuntansi tidak ditemukan untuk pembayaran ini.'
            ]);
        }
    }

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['status' => 'error', 'message' => 'Error: ' . $e->getMessage()]);
}
?>