<?php
/**
 * Provisi Management Module
 * Koperasi Management System
 */

require_once __DIR__ . '/config/database.php';
$db = getDB();

$pageTitle = 'Manajemen Provisi';
$pageSubtitle = 'Kelola data pemasukan dan pengeluaran provisi';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add' || $action === 'expense') {
        $tanggal = $_POST['tanggal'];
        $jumlah = (float)str_replace('.', '', $_POST['jumlah']);
        $keterangan = sanitize($_POST['keterangan']);
        $tipe = ($action === 'add') ? 'masuk' : 'keluar';
        
        try {
            $stmt = $db->prepare("INSERT INTO provisi (tanggal, keterangan, tipe, jumlah, created_by) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$tanggal, $keterangan, $tipe, $jumlah, $_SESSION['user_id']]);
            
            setFlash('success', 'Transaksi provisi berhasil disimpan.');
        } catch (Exception $e) {
            setFlash('danger', 'Gagal menyimpan transaksi: ' . $e->getMessage());
        }
        header('Location: provisi.php');
        exit;
    }
    
    if ($action === 'delete') {
        $id = $_POST['id'];
        $db->prepare("DELETE FROM provisi WHERE id = ?")->execute([$id]);
        setFlash('success', 'Transaksi berhasil dihapus.');
        header('Location: provisi.php');
        exit;
    }
}

// Fetch data
$search = $_GET['search'] ?? '';
$where = $search ? "WHERE keterangan LIKE ?" : "";
$params = $search ? ["%$search%"] : [];

// Statistics
$totalMasuk = $db->query("SELECT SUM(jumlah) FROM provisi WHERE tipe = 'masuk'")->fetchColumn() ?: 0;
$totalKeluar = $db->query("SELECT SUM(jumlah) FROM provisi WHERE tipe = 'keluar'")->fetchColumn() ?: 0;
$saldoAkhir = $totalMasuk - $totalKeluar;

$stmt = $db->prepare("SELECT * FROM provisi $where ORDER BY tanggal ASC, id ASC");
$stmt->execute($params);
$provisiList = $stmt->fetchAll();

include __DIR__ . '/includes/header.php';
?>

<!-- Summary Cards -->
<div class="stats-grid" style="grid-template-columns: repeat(3, 1fr); margin-bottom: 24px;">
    <div class="stat-card" style="padding: 20px; border-bottom: 3px solid #059669;">
        <div class="stat-info">
            <h3>Total Masuk</h3>
            <div class="stat-value" style="color: #059669;"><?= formatRupiah($totalMasuk) ?></div>
        </div>
        <div class="stat-icon" style="background: #ecfdf5; color: #059669;">
            <i class="fas fa-arrow-down"></i>
        </div>
    </div>
    <div class="stat-card" style="padding: 20px; border-bottom: 3px solid #dc2626;">
        <div class="stat-info">
            <h3>Total Keluar</h3>
            <div class="stat-value" style="color: #dc2626;"><?= formatRupiah($totalKeluar) ?></div>
        </div>
        <div class="stat-icon" style="background: #fef2f2; color: #dc2626;">
            <i class="fas fa-arrow-up"></i>
        </div>
    </div>
    <div class="stat-card" style="padding: 20px; border-bottom: 3px solid var(--primary-600);">
        <div class="stat-info">
            <h3>Saldo Provisi</h3>
            <div class="stat-value" style="color: var(--gray-900);"><?= formatRupiah($saldoAkhir) ?></div>
        </div>
        <div class="stat-icon" style="background: var(--primary-50); color: var(--primary-600);">
            <i class="fas fa-wallet"></i>
        </div>
    </div>
</div>

<style>
/* Reset and Premium Overrides */
.card-header {
    padding: 16px 24px;
    background: white;
}

.toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    width: 100%;
}

.search-box {
    flex: 1;
    max-width: 400px;
    position: relative;
}

.search-box i {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--gray-400);
}

.search-box input {
    width: 100%;
    padding: 10px 14px 10px 40px;
    border: 1.5px solid var(--gray-200);
    border-radius: 10px;
    font-size: 0.9rem;
    transition: all 0.2s;
}

.search-box input:focus {
    border-color: var(--primary-400);
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
    outline: none;
}

/* Premium Table Styling */
.provisi-table {
    width: 100%;
    border-collapse: collapse;
}

.provisi-table thead th {
    background: white;
    color: var(--gray-500);
    font-weight: 700;
    font-size: 0.72rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    padding: 12px 16px;
    border-bottom: 1px solid var(--gray-200);
    text-align: left;
}

.provisi-table tbody td {
    padding: 18px 16px;
    border-bottom: 1px solid var(--gray-100);
    vertical-align: middle;
    color: var(--gray-800);
    font-size: 0.9rem;
}

.provisi-table tr:hover {
    background-color: #f9fafb;
}

/* Alignments */
.col-no { width: 40px; color: var(--gray-400) !important; font-size: 0.8rem !important; }
.col-tgl { width: 120px; color: var(--gray-500) !important; }
.col-ket { font-weight: 500; }
.col-num { text-align: right !important; font-family: 'Inter', sans-serif; font-weight: 600; }

/* Financial Amounts */
.amount-plus { color: #047857; } /* Emerald 700 */
.amount-minus { color: #be123c; } /* Rose 700 */
.amount-total { color: var(--primary-700); font-weight: 700; }
.empty-val { color: var(--gray-200); font-weight: 300; }

/* Action Buttons */
.btn-delete-muted {
    background: none;
    border: none;
    color: var(--gray-300);
    padding: 6px;
    border-radius: 6px;
    transition: all 0.2s;
    cursor: pointer;
}

.btn-delete-muted:hover {
    color: #be123c;
    background: #fff1f2;
}

@media print {
    .btn, .toolbar, .stat-icon, .col-aksi, .modal, .sidebar, .topbar { display: none !important; }
    body { background: white; margin: 0; padding: 0; }
    .card { border: none; box-shadow: none; }
    .main-content { margin-left: 0 !important; }
    .table-responsive { overflow: visible !important; }
}
</style>

<div class="card">
    <div class="card-header">
        <div class="toolbar">
            <div style="display: flex; gap: 10px;">
                <button class="btn btn-primary" onclick="openModal('addModal')">
                    <i class="fas fa-plus"></i> Tambah Masuk
                </button>
                <button class="btn btn-danger" onclick="openModal('expenseModal')">
                    <i class="fas fa-minus"></i> Pengeluaran
                </button>
            </div>
            
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" placeholder="Cari keterangan..." value="<?= htmlspecialchars($search) ?>"
                       onkeydown="if(event.key==='Enter') { window.location='provisi.php?search='+this.value; }">
            </div>

            <div style="display: flex; gap: 8px;">
                 <a href="exports/provisi_export_excel.php<?= $search ? '?search='.urlencode($search) : '' ?>" class="btn btn-success" target="_blank" title="Export Excel">
                    <i class="fas fa-file-excel"></i>
                </a>
                 <a href="exports/provisi_export_pdf.php<?= $search ? '?search='.urlencode($search) : '' ?>" class="btn btn-danger" target="_blank" title="Cetak PDF">
                    <i class="fas fa-file-pdf"></i>
                </a>
                 <button class="btn btn-outline" onclick="window.print()" title="Cetak">
                    <i class="fas fa-print"></i>
                </button>
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="provisi-table">
            <thead>
                <tr>
                    <th class="col-no">NO</th>
                    <th class="col-tgl">TANGGAL</th>
                    <th class="col-ket">KETERANGAN</th>
                    <th class="col-num">MASUK</th>
                    <th class="col-num">KELUAR</th>
                    <th class="col-num">SALDO</th>
                    <th class="text-center">AKSI</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                if (empty($provisiList)): ?>
                    <tr><td colspan="7" class="text-center text-muted" style="padding: 60px;">Tidak ada data transaksi provisi</td></tr>
                <?php else: 
                    $no = 1;
                    // Calculate running saldo correctly based on sorted order
                    // Since we display latest first (reversed), we need to calculate in ASC order first
                    $allData = $db->query("SELECT * FROM provisi ORDER BY tanggal ASC, id ASC")->fetchAll();
                    $saldoMap = [];
                    $tempSaldo = 0;
                    foreach ($allData as $row) {
                        if ($row['tipe'] === 'masuk') $tempSaldo += $row['jumlah'];
                        else $tempSaldo -= $row['jumlah'];
                        $saldoMap[$row['id']] = $tempSaldo;
                    }
                    
                    // Filter based on search
                    $displayItems = $provisiList; // Already filtered by search in the initial query
                    
                    foreach ($displayItems as $item): ?>
                        <tr>
                            <td class="col-no"><?= $no++ ?></td>
                            <td class="col-tgl"><?= date('d/m/Y', strtotime($item['tanggal'])) ?></td>
                            <td class="col-ket"><?= htmlspecialchars($item['keterangan']) ?></td>
                            <td class="col-num">
                                <?php if($item['tipe'] === 'masuk'): ?>
                                    <span class="amount-plus"><?= formatRupiah($item['jumlah']) ?></span>
                                <?php else: ?>
                                    <span class="empty-val">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="col-num">
                                <?php if($item['tipe'] === 'keluar'): ?>
                                    <span class="amount-minus"><?= formatRupiah($item['jumlah']) ?></span>
                                <?php else: ?>
                                    <span class="empty-val">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="col-num">
                                <span class="amount-total"><?= formatRupiah($saldoMap[$item['id']]) ?></span>
                            </td>
                            <td class="text-center">
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus transaksi ini?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $item['id'] ?>">
                                    <button class="btn-delete-muted" title="Hapus"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add Modal -->
<div class="modal" id="addModal">
    <div class="modal-header">
        <h3><i class="fas fa-plus-circle text-primary"></i> Tambah Provisi Masuk</h3>
        <button class="modal-close" onclick="closeModal('addModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="add">
        <div class="modal-body">
            <div class="form-group">
                <label>Tanggal <span class="required">*</span></label>
                <input type="date" name="tanggal" class="form-control" required value="<?= date('Y-m-d') ?>">
            </div>
            <div class="form-group">
                <label>Jumlah (Rp) <span class="required">*</span></label>
                <input type="text" name="jumlah" class="form-control" required oninput="formatCurrencyInput(this)" placeholder="0">
            </div>
            <div class="form-group">
                <label>Keterangan <span class="required">*</span></label>
                <textarea name="keterangan" class="form-control" required placeholder="Contoh: Provisi pinjaman PNJ-0001"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addModal')">Batal</button>
            <button type="submit" class="btn btn-primary">Simpan</button>
        </div>
    </form>
</div>

<!-- Expense Modal -->
<div class="modal" id="expenseModal">
    <div class="modal-header">
        <h3><i class="fas fa-minus-circle text-danger"></i> Pengeluaran Provisi</h3>
        <button class="modal-close" onclick="closeModal('expenseModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="expense">
        <div class="modal-body">
            <div class="form-group">
                <label>Tanggal <span class="required">*</span></label>
                <input type="date" name="tanggal" class="form-control" required value="<?= date('Y-m-d') ?>">
            </div>
            <div class="form-group">
                <label>Jumlah (Rp) <span class="required">*</span></label>
                <input type="text" name="jumlah" class="form-control" required oninput="formatCurrencyInput(this)" placeholder="0">
            </div>
            <div class="form-group">
                <label>Keterangan <span class="required">*</span></label>
                <textarea name="keterangan" class="form-control" required placeholder="Contoh: Pembelian Alat Tulis Kantor"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('expenseModal')">Batal</button>
            <button type="submit" class="btn btn-danger">Simpan</button>
        </div>
    </form>
</div>

<script src="<?= ASSETS_URL ?>/js/app.js"></script>
<?php include __DIR__ . '/includes/footer.php'; ?>
