<?php

namespace App\Http\Controllers;

use App\Models\GeneratedDocument;
use App\Models\ExportJob;
use App\Models\EmailLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Mail;
use ZipArchive;

class ExportCenterController extends Controller
{
    public function index()
    {
        $documents = GeneratedDocument::with(['orderConfirmation', 'generator'])
            ->latest()
            ->paginate(20);

        $exportJobs = ExportJob::with('user')
            ->latest()
            ->limit(5)
            ->get();

        $emailLogs = EmailLog::with(['document', 'sender'])
            ->latest()
            ->limit(10)
            ->get();

        return view('admin.document-generator.export-center.index', compact('documents', 'exportJobs', 'emailLogs'));
    }

    public function bulkDownload(Request $request)
    {
        $validated = $request->validate([
            'document_ids' => 'required|array',
            'document_ids.*' => 'exists:generated_documents,id',
        ]);

        $documents = GeneratedDocument::whereIn('id', $validated['document_ids'])->get();

        if ($documents->isEmpty()) {
            return back()->with('error', 'No documents selected for download.');
        }

        $zip = new ZipArchive;
        $zipFileName = 'documents_export_' . time() . '.zip';
        $zipPath = storage_path('app/public/temp/' . $zipFileName);

        if (!is_dir(dirname($zipPath))) {
            mkdir(dirname($zipPath), 0755, true);
        }

        if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
            foreach ($documents as $document) {
                if (Storage::disk('public')->exists($document->file_path)) {
                    $filePath = Storage::disk('public')->path($document->file_path);
                    $zip->addFile($filePath, $document->file_name);
                }
            }
            $zip->close();
        }

        return response()->download($zipPath)->deleteFileAfterSend(true);
    }

    public function createExcelReport(Request $request)
    {
        $validated = $request->validate([
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'document_type' => 'nullable|in:commercial_invoice,packing_list,certificate_origin,bill_of_lading,inspection_certificate,shipping_label',
        ]);

        $exportJob = ExportJob::create([
            'user_id' => auth()->id(),
            'type' => 'excel_report',
            'filters' => $validated,
            'status' => 'pending',
        ]);

        return back()->with('success', 'Excel report generation started. You will be notified when it\'s ready.');
    }

    public function sendEmail(Request $request)
    {
        $validated = $request->validate([
            'document_id' => 'required|exists:generated_documents,id',
            'recipient_email' => 'required|email',
            'recipient_name' => 'nullable|string|max:255',
            'subject' => 'required|string|max:255',
            'message' => 'nullable|string',
        ]);

        $document = GeneratedDocument::findOrFail($validated['document_id']);

        try {
            // Create email log
            $emailLog = EmailLog::create([
                'generated_document_id' => $document->id,
                'recipient_email' => $validated['recipient_email'],
                'recipient_name' => $validated['recipient_name'],
                'subject' => $validated['subject'],
                'message' => $validated['message'],
                'sent_by' => auth()->id(),
                'status' => 'pending',
            ]);

            // Prepare email data
            $emailData = [
                'recipient_name' => $validated['recipient_name'] ?? $validated['recipient_email'],
                'subject' => $validated['subject'],
                'message_content' => $validated['message'] ?? 'Please find the attached document.',
                'document_name' => $document->file_name,
                'order_number' => $document->orderConfirmation->order_number ?? 'N/A',
            ];

            // Send actual email with attachment
            Mail::send([], $emailData, function ($message) use ($emailData, $validated, $document) {
                $message->to($validated['recipient_email'], $emailData['recipient_name'])
                        ->subject($emailData['subject'])
                        ->html($this->getEmailHtml($emailData));
                
                // Attach the document
                if (Storage::disk('public')->exists($document->file_path)) {
                    $filePath = Storage::disk('public')->path($document->file_path);
                    $message->attach($filePath, [
                        'as' => $document->file_name,
                        'mime' => 'application/pdf',
                    ]);
                }
            });

            // Update email log as sent
            $emailLog->update([
                'status' => 'sent',
                'sent_at' => now(),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Email sent successfully with document attachment!'
            ]);

        } catch (\Exception $e) {
            \Log::error('Email sending failed: ' . $e->getMessage());
            
            // Update email log as failed
            if (isset($emailLog)) {
                $emailLog->update([
                    'status' => 'failed',
                ]);
            }

            return response()->json([
                'success' => false,
                'message' => 'Failed to send email: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get HTML content for email
     */
    private function getEmailHtml($data)
    {
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #007bff; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background: #f9f9f9; }
                .footer { text-align: center; padding: 20px; color: #666; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Document Delivery</h2>
                </div>
                <div class='content'>
                    <p>Dear {$data['recipient_name']},</p>
                    <p>{$data['message_content']}</p>
                    <p><strong>Document Details:</strong></p>
                    <ul>
                        <li>Document: {$data['document_name']}</li>
                        <li>Order Number: {$data['order_number']}</li>
                    </ul>
                    <p>Please find the document attached with this email.</p>
                </div>
                <div class='footer'>
                    <p>Best regards,<br>Texsia App</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    public function getExportJobStatus(ExportJob $exportJob)
    {
        return response()->json([
            'status' => $exportJob->status,
            'progress' => $exportJob->progress_percentage,
            'download_url' => $exportJob->download_url,
        ]);
    }
}