<?php
session_start();
require_once '../config/config.php';
require_once 'PDFGenerator.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$receipt_ids = $_POST['receipt_ids'] ?? [];
$date_from = $_POST['date_from'] ?? null;
$date_to = $_POST['date_to'] ?? null;
$member_id = $_POST['member_id'] ?? null;

if (empty($receipt_ids) && !$date_from && !$date_to && !$member_id) {
    echo json_encode(['success' => false, 'message' => 'Please provide receipt IDs or date range']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Build query based on filters
    $whereConditions = [];
    $params = [];
    
    if (!empty($receipt_ids)) {
        $placeholders = str_repeat('?,', count($receipt_ids) - 1) . '?';
        $whereConditions[] = "r.id IN ($placeholders)";
        $params = array_merge($params, $receipt_ids);
    }
    
    if ($date_from) {
        $whereConditions[] = "r.created_at >= ?";
        $params[] = $date_from;
    }
    
    if ($date_to) {
        $whereConditions[] = "r.created_at <= ?";
        $params[] = $date_to . ' 23:59:59';
    }
    
    if ($member_id) {
        $whereConditions[] = "r.member_id = ?";
        $params[] = $member_id;
    }
    
    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
    
    // Get receipts data
    $stmt = $conn->prepare("
        SELECT 
            r.*,
            m.first_name,
            m.last_name,
            m.kso_id,
            m.email,
            m.phone,
            f.payment_method,
            f.payment_date,
            f.description as payment_description
        FROM receipts r
        LEFT JOIN members m ON r.member_id = m.id
        LEFT JOIN finance f ON r.transaction_id = f.id
        $whereClause
        ORDER BY r.created_at DESC
    ");
    $stmt->execute($params);
    $receipts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($receipts)) {
        echo json_encode(['success' => false, 'message' => 'No receipts found']);
        exit();
    }
    
    // Create a ZIP file for bulk download
    $zipFile = tempnam(sys_get_temp_dir(), 'receipts_bulk_');
    $zip = new ZipArchive();
    
    if ($zip->open($zipFile, ZipArchive::CREATE) !== TRUE) {
        echo json_encode(['success' => false, 'message' => 'Cannot create ZIP file']);
        exit();
    }
    
    foreach ($receipts as $receipt) {
        // Prepare data for PDF generation
        $pdfData = [
            'number' => $receipt['receipt_number'],
            'date' => $receipt['created_at'],
            'member_name' => $receipt['first_name'] . ' ' . $receipt['last_name'],
            'kso_id' => $receipt['kso_id'],
            'email' => $receipt['email'],
            'phone' => $receipt['phone'],
            'amount' => $receipt['amount'],
            'transaction_type' => $receipt['transaction_type'],
            'payment_method' => $receipt['payment_method'],
            'description' => $receipt['payment_description'] ?: 'Payment received',
            'status' => 'paid',
            'include_qr' => true,
            'digital_signature' => true
        ];
        
        // Generate PDF
        $pdf = new ReceiptPDFGenerator();
        $pdf->generateReceipt($pdfData);
        
        // Add to ZIP
        $zip->addFromString(
            'receipt_' . $receipt['receipt_number'] . '.pdf',
            $pdf->Output('', 'S')
        );
    }
    
    $zip->close();
    
    // Output the ZIP file
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="receipts_bulk_' . date('Y-m-d') . '.zip"');
    header('Content-Length: ' . filesize($zipFile));
    
    readfile($zipFile);
    
    // Clean up
    unlink($zipFile);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error generating bulk PDFs: ' . $e->getMessage()]);
}
?>
