<?php
/**
 * Export Anggota - Preview & Download
 * Supports: PDF, Word, Excel
 */

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/auth.php';
requireAdmin();

$db = getDB();

// Get filters
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';

// Build query
$where = "WHERE 1=1";
$params = [];

if ($search) {
    $where .= " AND (nama LIKE ? OR no_anggota LIKE ? OR telepon LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status) {
    $where .= " AND status = ?";
    $params[] = $status;
}

// Get all members
$stmt = $db->prepare("SELECT * FROM anggota $where ORDER BY nama ASC");
$stmt->execute($params);
$members = $stmt->fetchAll();

$totalMembers = count($members);

// Handle export action
$action = isset($_GET['action']) ? $_GET['action'] : 'preview';
$format = isset($_GET['format']) ? $_GET['format'] : 'pdf';

if ($action === 'download') {
    if ($format === 'pdf') {
        exportPDF();
    } elseif ($format === 'word') {
        exportWord();
    } elseif ($format === 'excel') {
        exportExcel();
    }
    exit;
}

function exportPDF() {
    global $members, $totalMembers, $search, $status;
    
    header('Content-Type: text/html; charset=utf-8');
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Data Anggota Koperasi</title>
        <style>
            @page { size: A4 landscape; margin: 15mm; }
            body { font-family: Arial, sans-serif; margin: 0; padding: 15px; color: #333; font-size: 10px; }
            .header { text-align: center; margin-bottom: 20px; border-bottom: 3px solid #2563eb; padding-bottom: 15px; }
            .header h1 { margin: 0; color: #1e40af; font-size: 20px; }
            .header h2 { margin: 8px 0 5px; color: #374151; font-size: 16px; }
            .filter-info { margin-bottom: 15px; background: #f3f4f6; padding: 10px; border-radius: 5px; }
            table.data-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
            table.data-table th { background: #2563eb; color: white; padding: 8px; text-align: left; font-size: 10px; }
            table.data-table td { padding: 6px 8px; border-bottom: 1px solid #e5e7eb; font-size: 10px; }
            table.data-table tr:nth-child(even) { background: #f9fafb; }
            .badge { padding: 2px 6px; border-radius: 3px; font-size: 9px; font-weight: 600; }
            .badge-success { background: #d1fae5; color: #065f46; }
            .badge-danger { background: #fee2e2; color: #7f1d1d; }
            .summary { margin-top: 20px; background: #f3f4f6; padding: 15px; border-radius: 8px; }
            .signature { margin-top: 40px; display: flex; justify-content: space-between; }
            .signature-box { text-align: center; width: 200px; }
            .signature-box .line { margin-top: 70px; border-top: 2px solid #333; padding-top: 5px; }
            @media print {
                body { padding: 0; }
                .no-print { display: none !important; }
            }
        </style>
    </head>
    <body>
        <div class="no-print" style="background: #eff6ff; padding: 12px; text-align: center; margin-bottom: 15px; border-radius: 8px;">
            <button onclick="window.print()" style="padding: 8px 16px; background: #2563eb; color: white; border: none; border-radius: 5px; cursor: pointer; margin: 0 5px;">🖨️ Print</button>
            <a href="?action=download&format=pdf" style="padding: 8px 16px; background: #059669; color: white; text-decoration: none; border-radius: 5px; margin: 0 5px;">💾 PDF</a>
            <a href="?format=word" style="padding: 8px 16px; background: #2563eb; color: white; text-decoration: none; border-radius: 5px; margin: 0 5px;">📝 Word</a>
            <a href="?format=excel" style="padding: 8px 16px; background: #10b981; color: white; text-decoration: none; border-radius: 5px; margin: 0 5px;">📊 Excel</a>
            <a href="anggota.php" style="padding: 8px 16px; background: #6b7280; color: white; text-decoration: none; border-radius: 5px; margin: 0 5px;">← Kembali</a>
        </div>
        
        <div class="header">
            <h1>KOPERASI TSUROYA</h1>
            <h2>DATA ANGGOTA KOPERASI</h2>
        </div>
        
        <?php if ($search || $status): ?>
        <div class="filter-info">
            <?php if ($search): ?><strong>Pencarian:</strong> <?= htmlspecialchars($search) ?><br><?php endif; ?>
            <?php if ($status): ?><strong>Status:</strong> <?= ucfirst($status) ?><?php endif; ?>
        </div>
        <?php endif; ?>
        
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width: 40px;">No</th>
                    <th style="width: 100px;">No. Anggota</th>
                    <th>Nama</th>
                    <th style="width: 80px;">NIK</th>
                    <th style="width: 70px;">TTL</th>
                    <th style="width: 40px;">JK</th>
                    <th style="width: 120px;">Alamat</th>
                    <th style="width: 80px;">Telepon</th>
                    <th style="width: 80px;">Status</th>
                </tr>
            </thead>
            <tbody>
                <?php $no = 1; foreach ($members as $m): ?>
                <tr>
                    <td style="text-align: center;"><?= $no++ ?></td>
                    <td><?= htmlspecialchars($m['no_anggota']) ?></td>
                    <td><?= htmlspecialchars($m['nama']) ?></td>
                    <td><?= htmlspecialchars($m['nik'] ?? '-') ?></td>
                    <td><?= htmlspecialchars(($m['tempat_lahir'] ?? '') . ', ' . ($m['tanggal_lahir'] ? date('d/m/Y', strtotime($m['tanggal_lahir'])) : '')) ?></td>
                    <td style="text-align: center;"><?= $m['jenis_kelamin'] ?></td>
                    <td><?= htmlspecialchars(substr($m['alamat'] ?? '-', 0, 30)) ?></td>
                    <td><?= htmlspecialchars($m['telepon'] ?? '-') ?></td>
                    <td style="text-align: center;">
                        <span class="badge <?= $m['status'] === 'aktif' ? 'badge-success' : 'badge-danger' ?>">
                            <?= ucfirst($m['status']) ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <div class="summary">
            <strong>Total Anggota:</strong> <?= $totalMembers ?> orang
        </div>
        
        <div class="signature">
            <div class="signature-box">
                <p>Mengetahui,</p>
                <p>Ketua Koperasi</p>
                <div class="line">(_________________)</div>
            </div>
            <div class="signature-box">
                <p>Sekretaris</p>
                <div class="line">(_________________)</div>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

function exportWord() {
    global $members, $totalMembers, $search, $status;
    
    header('Content-Type: application/msword');
    header('Content-Disposition: attachment; filename="Data_Anggota_' . date('Ymd') . '.doc"');
    ?>
    <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'>
    <head>
        <meta charset="utf-8">
        <title>Data Anggota</title>
        <style>
            body { font-family: Arial, sans-serif; font-size: 10pt; }
            .header { text-align: center; margin-bottom: 15px; }
            .header h1 { margin: 0; font-size: 16pt; }
            .header h2 { margin: 8px 0 5px; font-size: 14pt; }
            table { width: 100%; border-collapse: collapse; }
            th { background-color: #2563eb; color: white; padding: 6px; text-align: left; font-size: 10pt; }
            td { padding: 6px; border: 1px solid #ddd; font-size: 10pt; }
        </style>
    </head>
    <body>
        <div class="header">
            <h1>KOPERASI TSUROYA</h1>
            <h2>DATA ANGGOTA KOPERASI</h2>
        </div>
        
        <table>
            <tr>
                <th>No</th>
                <th>No. Anggota</th>
                <th>Nama</th>
                <th>NIK</th>
                <th>TTL</th>
                <th>JK</th>
                <th>Telepon</th>
                <th>Status</th>
            </tr>
            <?php $no = 1; foreach ($members as $m): ?>
            <tr>
                <td style="text-align: center;"><?= $no++ ?></td>
                <td><?= htmlspecialchars($m['no_anggota']) ?></td>
                <td><?= htmlspecialchars($m['nama']) ?></td>
                <td><?= htmlspecialchars($m['nik'] ?? '-') ?></td>
                <td><?= htmlspecialchars(($m['tempat_lahir'] ?? '') . ', ' . ($m['tanggal_lahir'] ? date('d/m/Y', strtotime($m['tanggal_lahir'])) : '')) ?></td>
                <td style="text-align: center;"><?= $m['jenis_kelamin'] ?></td>
                <td><?= htmlspecialchars($m['telepon'] ?? '-') ?></td>
                <td style="text-align: center;"><?= ucfirst($m['status']) ?></td>
            </tr>
            <?php endforeach; ?>
        </table>
        
        <p style="margin-top: 15px;"><strong>Total Anggota:</strong> <?= $totalMembers ?> orang</p>
    </body>
    </html>
    <?php
    exit;
}

function exportExcel() {
    global $members, $totalMembers;
    
    $filename = "Data_Anggota_" . date('Ymd');
    $tmpfile = tempnam(sys_get_temp_dir(), 'xlsx_');
    
    $zip = new ZipArchive();
    if ($zip->open($tmpfile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === false) {
        die('Gagal membuat file Excel');
    }
    
    $sheetData = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<cols>
<col min="1" max="1" width="5" customWidth="1"/>
<col min="2" max="2" width="15" customWidth="1"/>
<col min="3" max="3" width="25" customWidth="1"/>
<col min="4" max="4" width="18" customWidth="1"/>
<col min="5" max="5" width="25" customWidth="1"/>
<col min="6" max="6" width="5" customWidth="1"/>
<col min="7" max="7" width="12" customWidth="1"/>
<col min="8" max="8" width="12" customWidth="1"/>
<col min="9" max="9" width="10" customWidth="1"/>
</cols><sheetData>';

    $sheetData .= '<row r="1"><c r="A1" t="str"><v>KOPERASI TSUROYYA</v></c></row>';
    $sheetData .= '<row r="2"><c r="A2" t="str"><v>DATA ANGGOTA KOPERASI</v></c></row>';
    $sheetData .= '<row r="3"/>';
    
    $headers = ['No', 'No. Anggota', 'Nama', 'NIK', 'Tempat/Tgl Lahir', 'JK', 'Telepon', 'Email', 'Status'];
    $sheetData .= '<row r="4">';
    foreach ($headers as $i => $header) {
        $col = chr(65 + $i);
        $sheetData .= '<c r="' . $col . '4" t="str"><v>' . $header . '</v></c>';
    }
    $sheetData .= '</row>';
    
    $rowNum = 5;
    $no = 1;
    foreach ($members as $m) {
        $ttl = ($m['tempat_lahir'] ?? '') . ', ' . ($m['tanggal_lahir'] ? date('d/m/Y', strtotime($m['tanggal_lahir'])) : '');
        $sheetData .= '<row r="' . $rowNum . '">';
        $sheetData .= '<c r="A' . $rowNum . '"><v>' . $no . '</v></c>';
        $sheetData .= '<c r="B' . $rowNum . '" t="str"><v>' . htmlspecialchars($m['no_anggota']) . '</v></c>';
        $sheetData .= '<c r="C' . $rowNum . '" t="str"><v>' . htmlspecialchars($m['nama']) . '</v></c>';
        $sheetData .= '<c r="D' . $rowNum . '" t="str"><v>' . htmlspecialchars($m['nik'] ?? '-') . '</v></c>';
        $sheetData .= '<c r="E' . $rowNum . '" t="str"><v>' . htmlspecialchars($ttl) . '</v></c>';
        $sheetData .= '<c r="F' . $rowNum . '" t="str"><v>' . $m['jenis_kelamin'] . '</v></c>';
        $sheetData .= '<c r="G' . $rowNum . '" t="str"><v>' . htmlspecialchars($m['telepon'] ?? '-') . '</v></c>';
        $sheetData .= '<c r="H' . $rowNum . '" t="str"><v>' . htmlspecialchars($m['email'] ?? '-') . '</v></c>';
        $sheetData .= '<c r="I' . $rowNum . '" t="str"><v>' . $m['status'] . '</v></c>';
        $sheetData .= '</row>';
        $rowNum++;
        $no++;
    }
    
    $sheetData .= '<row r="' . $rowNum . '"><c r="C' . $rowNum . '" t="str"><v>Total Anggota</v></c><c r="D' . $rowNum . '"><v>' . $totalMembers . '</v></c></row>';
    
    $sheetData .= '</sheetData></worksheet>';
    $zip->addFromString('xl/worksheets/sheet1.xml', $sheetData);
    
    $contentTypes = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
</Types>';
    $zip->addFromString('[Content_Types].xml', $contentTypes);
    
    $rels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
</Relationships>';
    $zip->addFromString('_rels/.rels', $rels);
    
    $workbookRels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
</Relationships>';
    $zip->addFromString('xl/_rels/workbook.xml.rels', $workbookRels);
    
    $workbook = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets><sheet name="Anggota" sheetId="1" r:id="rId1"/></sheets>
</workbook>';
    $zip->addFromString('xl/workbook.xml', $workbook);
    
    $styles = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts>
<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>
<borders count="1"><border><left/><right/><top/><bottom/></border></borders>
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
<cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs>
</styleSheet>';
    $zip->addFromString('xl/styles.xml', $styles);
    
    $zip->close();
    
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $filename . '.xlsx"');
    header('Content-Length: ' . filesize($tmpfile));
    header('Cache-Control: no-cache');
    
    readfile($tmpfile);
    unlink($tmpfile);
    exit;
}

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

<style>
    .export-actions { display: flex; gap: 10px; margin: 20px 0; flex-wrap: wrap; }
    .export-btn { padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; transition: all 0.3s; }
    .export-btn:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
    .btn-pdf { background: #dc2626; color: white; }
    .btn-word { background: #2563eb; color: white; }
    .btn-excel { background: #10b981; color: white; }
    .btn-back { background: #6b7280; color: white; }
    .preview-frame { width: 100%; height: 600px; border: 2px solid #e5e7eb; border-radius: 8px; margin-top: 20px; }
    .info-card { background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
</style>

<div class="info-card">
    <h2 style="margin-top: 0;">📄 Export Preview - Data Anggota</h2>
    <p><strong>Jumlah Anggota:</strong> <?= $totalMembers ?></p>
    <?php if ($search): ?><p><strong>Pencarian:</strong> <?= htmlspecialchars($search) ?></p><?php endif; ?>
    <?php if ($status): ?><p><strong>Filter Status:</strong> <?= ucfirst($status) ?></p><?php endif; ?>
</div>

<div class="export-actions">
    <a href="?format=pdf&action=preview" class="export-btn btn-pdf">📕 Preview PDF</a>
    <a href="?format=word&action=preview" class="export-btn btn-word">📘 Preview Word</a>
    <a href="?format=excel&action=preview" class="export-btn btn-excel">📗 Preview Excel</a>
    <a href="anggota.php" class="export-btn btn-back">← Kembali</a>
</div>

<?php
if ($format === 'pdf' && $action === 'preview'):
?>
    <iframe src="?format=pdf&action=download" class="preview-frame"></iframe>
<?php elseif ($format === 'word' && $action === 'preview'): ?>
    <div class="info-card">
        <h3>📘 Preview Word</h3>
        <p>Klik tombol di bawah untuk melihat atau download file Word:</p>
        <a href="?format=word&action=download" class="export-btn btn-word" target="_blank">📝 Open / Download Word</a>
    </div>
<?php elseif ($format === 'excel' && $action === 'preview'): ?>
    <div class="info-card">
        <h3>📗 Preview Excel</h3>
        <p>Klik tombol di bawah untuk melihat atau download file Excel:</p>
        <a href="?format=excel&action=download" class="export-btn btn-excel" target="_blank">📊 Open / Download Excel</a>
    </div>
<?php endif; ?>
