<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ContactRequest;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ContactRequestAdminController extends Controller
{
    public function index(Request $request): View
    {
        $query = ContactRequest::query();

        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        if ($request->filled('search')) {
            $search = trim((string) $request->search);
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('organization', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhere('message', 'like', "%{$search}%");
            });
        }

        $requests = $query->orderByDesc('created_at')
            ->paginate(20)
            ->withQueryString();

        $stats = [
            'total' => ContactRequest::count(),
            'new' => ContactRequest::where('status', ContactRequest::STATUS_NEW)->count(),
            'in_progress' => ContactRequest::where('status', ContactRequest::STATUS_IN_PROGRESS)->count(),
            'resolved' => ContactRequest::where('status', ContactRequest::STATUS_RESOLVED)->count(),
        ];

        return view('super-admin.contact-requests.index', [
            'requests' => $requests,
            'stats' => $stats,
            'statuses' => ContactRequest::STATUSES,
            'filters' => [
                'status' => $request->get('status', 'all'),
                'search' => $request->get('search', ''),
            ],
        ]);
    }

    public function show(int $id): View
    {
        $contact = ContactRequest::findOrFail($id);
        $contact->markRead();

        return view('super-admin.contact-requests.show', [
            'contact' => $contact,
            'statuses' => ContactRequest::STATUSES,
        ]);
    }

    public function updateStatus(Request $request, int $id): RedirectResponse|JsonResponse
    {
        $data = $request->validate([
            'status' => ['required', 'string', 'in:' . implode(',', array_keys(ContactRequest::STATUSES))],
            'admin_notes' => ['nullable', 'string', 'max:5000'],
        ]);

        $contact = ContactRequest::findOrFail($id);
        $contact->status = $data['status'];
        if (array_key_exists('admin_notes', $data)) {
            $contact->admin_notes = $data['admin_notes'];
        }
        if ($data['status'] === ContactRequest::STATUS_RESOLVED && ! $contact->responded_at) {
            $contact->responded_at = now();
        }
        $contact->save();

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Request updated.',
                'status' => $contact->status,
            ]);
        }

        return redirect()
            ->route('super.admin.contact-requests.show', $contact->id)
            ->with('success', 'Contact request updated.');
    }

    public function destroy(int $id): RedirectResponse|JsonResponse
    {
        $contact = ContactRequest::findOrFail($id);
        $contact->delete();

        if (request()->expectsJson()) {
            return response()->json(['success' => true]);
        }

        return redirect()
            ->route('super.admin.contact-requests.index')
            ->with('success', 'Contact request deleted.');
    }

    /**
     * Export contact requests as CSV or PDF.
     *
     * Honors the same filters as the index view (status + search + date range)
     * so admins can "export the current view".
     */
    public function export(Request $request): StreamedResponse|Response|RedirectResponse
    {
        $format = strtolower((string) $request->get('format', 'csv'));
        if (! in_array($format, ['csv', 'pdf', 'excel'], true)) {
            $format = 'csv';
        }

        $query = ContactRequest::query();

        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        if ($request->filled('search')) {
            $search = trim((string) $request->search);
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('organization', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhere('message', 'like', "%{$search}%");
            });
        }

        if ($request->filled('start_date')) {
            try {
                $query->whereDate('created_at', '>=', Carbon::parse($request->start_date)->toDateString());
            } catch (\Throwable) {
                // ignore bad date
            }
        }

        if ($request->filled('end_date')) {
            try {
                $query->whereDate('created_at', '<=', Carbon::parse($request->end_date)->toDateString());
            } catch (\Throwable) {
                // ignore bad date
            }
        }

        $requests = $query->orderByDesc('created_at')->limit(5000)->get();

        $dateStamp = now()->format('Y-m-d');

        try {
            if ($format === 'pdf') {
                return $this->exportToPdf($requests, $dateStamp);
            }

            return $this->exportToCsv($requests, $dateStamp);
        } catch (\Throwable $e) {
            Log::error('Contact requests export failed', [
                'error' => $e->getMessage(),
                'format' => $format,
            ]);

            return redirect()
                ->route('super.admin.contact-requests.index')
                ->with('error', 'Export failed: ' . $e->getMessage());
        }
    }

    private function exportToCsv($requests, string $dateStamp): StreamedResponse
    {
        $filename = "contact-requests-{$dateStamp}.csv";
        $headers = [
            'Content-Type' => 'text/csv; charset=UTF-8',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
            'Cache-Control' => 'no-store, no-cache, must-revalidate',
            'Pragma' => 'no-cache',
        ];

        $callback = function () use ($requests) {
            $out = fopen('php://output', 'w');
            // BOM so Excel opens UTF-8 correctly
            fwrite($out, "\xEF\xBB\xBF");

            fputcsv($out, [
                'ID', 'Received', 'Name', 'Email', 'Phone',
                'Organization', 'Message', 'Source', 'Status',
                'Read at', 'Responded at', 'IP address', 'Admin notes',
            ]);

            foreach ($requests as $r) {
                fputcsv($out, [
                    $r->id,
                    optional($r->created_at)->format('Y-m-d H:i:s'),
                    (string) $r->name,
                    (string) $r->email,
                    (string) ($r->phone ?? ''),
                    (string) ($r->organization ?? ''),
                    (string) ($r->message ?? ''),
                    (string) ($r->source ?? ''),
                    (string) ($r->status ?? ''),
                    optional($r->read_at)->format('Y-m-d H:i:s'),
                    optional($r->responded_at)->format('Y-m-d H:i:s'),
                    (string) ($r->ip_address ?? ''),
                    (string) ($r->admin_notes ?? ''),
                ]);
            }

            fclose($out);
        };

        return response()->stream($callback, 200, $headers);
    }

    private function exportToPdf($requests, string $dateStamp): Response
    {
        $html = $this->buildPdfHtml($requests);
        $filename = "contact-requests-{$dateStamp}.pdf";

        if (class_exists(\Dompdf\Dompdf::class)) {
            $dompdf = new \Dompdf\Dompdf([
                'isRemoteEnabled' => true,
                'isHtml5ParserEnabled' => true,
            ]);
            $dompdf->loadHtml($html, 'UTF-8');
            $dompdf->setPaper('A4', 'landscape');
            $dompdf->render();

            return response($dompdf->output(), 200, [
                'Content-Type' => 'application/pdf',
                'Content-Disposition' => "attachment; filename=\"{$filename}\"",
                'Cache-Control' => 'no-store, no-cache, must-revalidate',
            ]);
        }

        // Fallback to a self-contained HTML file the user can print.
        $htmlFilename = "contact-requests-{$dateStamp}.html";

        return response($html, 200, [
            'Content-Type' => 'text/html; charset=UTF-8',
            'Content-Disposition' => "attachment; filename=\"{$htmlFilename}\"",
        ]);
    }

    private function buildPdfHtml($requests): string
    {
        $statusColors = [
            'new' => '#92400e',
            'in_progress' => '#055160',
            'resolved' => '#0f5132',
            'archived' => '#41464b',
        ];
        $statusBg = [
            'new' => '#fff3cd',
            'in_progress' => '#cff4fc',
            'resolved' => '#d1e7dd',
            'archived' => '#e2e3e5',
        ];

        $rows = '';
        foreach ($requests as $r) {
            $msg = trim((string) ($r->message ?? ''));
            if (mb_strlen($msg) > 220) {
                $msg = mb_substr($msg, 0, 217) . '…';
            }
            $color = $statusColors[$r->status] ?? '#1f2937';
            $bg = $statusBg[$r->status] ?? '#e5e7eb';

            $rows .= '<tr>'
                . '<td>' . e($r->id) . '</td>'
                . '<td>' . e(optional($r->created_at)->format('d M Y H:i') ?? '') . '</td>'
                . '<td><strong>' . e((string) $r->name) . '</strong><br><span style="color:#6b7280;font-size:9px;">' . e((string) $r->email) . '</span></td>'
                . '<td>' . e((string) ($r->organization ?? '')) . '</td>'
                . '<td>' . e((string) ($r->phone ?? '')) . '</td>'
                . '<td style="max-width:280px;">' . nl2br(e($msg)) . '</td>'
                . '<td><span style="background:' . $bg . ';color:' . $color . ';padding:3px 8px;border-radius:8px;font-size:9px;font-weight:700;text-transform:uppercase;">' . e((string) $r->status_label) . '</span></td>'
                . '</tr>';
        }

        if ($rows === '') {
            $rows = '<tr><td colspan="7" style="text-align:center;color:#6b7280;padding:30px;">No contact requests match the selected filters.</td></tr>';
        }

        $count = $requests->count();
        $newCount = ContactRequest::where('status', ContactRequest::STATUS_NEW)->count();
        $resolvedCount = ContactRequest::where('status', ContactRequest::STATUS_RESOLVED)->count();
        $totalCount = ContactRequest::count();

        return '
        <!DOCTYPE html>
        <html><head><meta charset="UTF-8"><title>Contact Requests Export</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 18px; color:#1f2937; font-size: 11px; }
            h1 { color: #0B4F2E; margin: 0 0 4px; font-size: 20px; }
            h2 { color: #374151; margin: 0 0 16px; font-size: 12px; font-weight: 500; }
            .header { text-align: center; border-bottom: 2px solid #0B4F2E; padding-bottom: 8px; margin-bottom: 16px; }
            .summary { display: table; width: 100%; margin-bottom: 14px; table-layout: fixed; }
            .summary-box { display: table-cell; padding: 10px; border: 1px solid #d1d5db; border-radius: 4px; text-align: center; background:#f9fafb; width: 25%; }
            .summary-box .label { font-size: 9px; color: #6b7280; text-transform: uppercase; letter-spacing: 0.05em; }
            .summary-box .value { font-size: 18px; font-weight: 800; color: #0B4F2E; margin-top: 4px; }
            table { width: 100%; border-collapse: collapse; }
            th { background: #0B4F2E; color: #fff; padding: 8px; font-size: 10px; text-align: left; text-transform: uppercase; letter-spacing: 0.04em; }
            td { padding: 7px 8px; border-bottom: 1px solid #e5e7eb; font-size: 10px; vertical-align: top; }
            tr:nth-child(even) td { background: #f9fafb; }
            .footer { margin-top: 18px; text-align: center; font-size: 9px; color: #94a3b8; border-top: 1px solid #e5e7eb; padding-top: 8px; }
        </style></head>
        <body>
            <div class="header">
                <h1>WEPESI HOTEL MANAGEMENT SOULUTION</h1>
                <h2>Contact Requests Export</h2>
                <p style="margin:0;font-size:10px;color:#6b7280;">Generated ' . date('d M Y H:i:s') . '</p>
            </div>
            <div class="summary">
                <div class="summary-box"><div class="label">In this export</div><div class="value">' . $count . '</div></div>
                <div class="summary-box"><div class="label">New (system-wide)</div><div class="value">' . $newCount . '</div></div>
                <div class="summary-box"><div class="label">Resolved</div><div class="value">' . $resolvedCount . '</div></div>
                <div class="summary-box"><div class="label">Total received</div><div class="value">' . $totalCount . '</div></div>
            </div>
            <table>
                <thead>
                    <tr>
                        <th style="width:32px;">#</th>
                        <th style="width:90px;">Received</th>
                        <th style="width:140px;">From</th>
                        <th style="width:110px;">Organization</th>
                        <th style="width:90px;">Phone</th>
                        <th>Message</th>
                        <th style="width:80px;">Status</th>
                    </tr>
                </thead>
                <tbody>' . $rows . '</tbody>
            </table>
            <div class="footer">
                <p>WEPESI Super Admin · This document is automatically generated.</p>
            </div>
        </body></html>';
    }
}
