<?php
require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../includes/admin-functions.php';

// Check admin login
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Export format
$format = isset($_GET['format']) ? strtolower($_GET['format']) : 'csv';

// Filters
$role = isset($_GET['role']) ? $_GET['role'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build query conditions
$conditions = [];
$params = [];

if (!empty($role) && in_array($role, ['admin', 'customer'])) {
    $conditions[] = "role = ?";
    $params[] = $role;
}

if (!empty($status) && in_array($status, ['active', 'inactive'])) {
    $conditions[] = "status = ?";
    $params[] = $status;
}

if (!empty($search)) {
    $conditions[] = "(name LIKE ? OR email LIKE ? OR phone LIKE ?)";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
}

$where_clause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";

// Get users for export
$sql = "
    SELECT 
        u.id, u.name, u.email, u.phone, u.address, 
        u.city, u.zip, u.role, u.status, u.created_at,
        (SELECT COUNT(*) FROM orders WHERE user_id = u.id) as order_count
    FROM 
        users u
    {$where_clause}
    ORDER BY u.id DESC
";

$users = get_rows($sql, $params);

// Filename
$filename = 'hugong-korisnici-' . date('Y-m-d');

// Headers
$headers = [
    'ID', 'Ime i prezime', 'Email', 'Telefon', 
    'Adresa', 'Grad', 'Poštanski broj', 
    'Uloga', 'Status', 'Broj porudžbina', 'Datum registracije'
];

// Prepare data
$data = [];
foreach ($users as $user) {
    $data[] = [
        $user['id'],
        $user['name'],
        $user['email'],
        $user['phone'],
        $user['address'],
        $user['city'],
        $user['zip'],
        $user['role'] === 'admin' ? 'Administrator' : 'Kupac',
        $user['status'] === 'active' ? 'Aktivan' : 'Neaktivan',
        $user['order_count'],
        date('d.m.Y. H:i', strtotime($user['created_at']))
    ];
}

// Export based on format
switch ($format) {
    case 'csv':
        export_csv($filename, $headers, $data);
        break;
    case 'excel':
        export_excel($filename, $headers, $data);
        break;
    default:
        export_csv($filename, $headers, $data);
        break;
}

// CSV Export Function
function export_csv($filename, $headers, $data) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
    
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // UTF-8 BOM
    
    fputcsv($output, $headers, ';');
    
    foreach ($data as $row) {
        fputcsv($output, $row, ';');
    }
    
    fclose($output);
    exit;
}

// Excel Export Function
function export_excel($filename, $headers, $data) {
    if (!class_exists('PhpOffice\PhpSpreadsheet\Spreadsheet')) {
        export_csv($filename, $headers, $data);
        return;
    }
    
    require_once '../../vendor/autoload.php';
    
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    
    // Add headers
    $col = 1;
    foreach ($headers as $header) {
        $sheet->setCellValueByColumnAndRow($col++, 1, $header);
    }
    
    // Add data
    $row = 2;
    foreach ($data as $rowData) {
        $col = 1;
        foreach ($rowData as $value) {
            $sheet->setCellValueByColumnAndRow($col++, $row, $value);
        }
        $row++;
    }
    
    // Style headers
    $lastColumn = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(count($headers));
    $headerRange = 'A1:' . $lastColumn . '1';
    
    $sheet->getStyle($headerRange)->getFont()->setBold(true);
    $sheet->getStyle($headerRange)->getFill()
        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
        ->getStartColor()->setRGB('DDDDDD');
    
    // Auto-size columns
    foreach (range('A', $lastColumn) as $columnID) {
        $sheet->getColumnDimension($columnID)->setAutoSize(true);
    }
    
    // Create writer and send file
    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $filename . '.xlsx"');
    header('Cache-Control: max-age=0');
    
    $writer->save('php://output');
    exit;
}
?>