<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\AdminReplyMail;

class ContactController extends Controller
{
    /**
     * Display a listing of contacts.
     */
    public function index(Request $request)
    {
        $query = Contact::query();

        // Filter by status
        if ($request->has('status') && $request->status != 'all') {
            $query->where('status', $request->status);
        }

        // Filter by search
        if ($request->has('search') && $request->search) {
            $query->where(function($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('email', 'like', '%' . $request->search . '%')
                  ->orWhere('subject', 'like', '%' . $request->search . '%');
            });
        }

        $contacts = $query->orderBy('created_at', 'desc')->paginate(15);
        
        // Get statistics
        $stats = [
            'total' => Contact::count(),
            'pending' => Contact::where('status', 'pending')->count(),
            'read' => Contact::whereNotNull('read_at')->count(),
            'replied' => Contact::where('status', 'replied')->count(),
            'unread' => Contact::whereNull('read_at')->count(),
        ];

        return view('admin.contacts.index', compact('contacts', 'stats'));
    }

    /**
     * Display the specified contact.
     */
    public function show($id)
    {
        $contact = Contact::findOrFail($id);
        
        // Mark as read if not already
        $contact->markAsRead();
        
        // Update status to read if pending
        if ($contact->status == 'pending') {
            $contact->update(['status' => 'read']);
        }

        return view('admin.contacts.show', compact('contact'));
    }

    /**
     * Reply to contact.
     */
    public function reply(Request $request, $id)
    {
        $request->validate([
            'reply_message' => 'required|string|min:10',
            'send_copy' => 'boolean'
        ]);

        $contact = Contact::findOrFail($id);
        
        try {
            // Send email reply
            Mail::to($contact->email)
                ->send(new AdminReplyMail($contact, $request->reply_message));
            
            // Update contact record
            $contact->markAsReplied();
            $contact->update([
                'status' => 'replied',
                'admin_note' => $request->reply_message
            ]);
            
            return redirect()
                ->route('admin.contacts.index')
                ->with('success', 'Balasan berhasil dikirim ke ' . $contact->email);
                
        } catch (\Exception $e) {
            return redirect()
                ->back()
                ->with('error', 'Gagal mengirim balasan: ' . $e->getMessage());
        }
    }

    /**
     * Update contact status.
     */
    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:pending,read,replied,archived'
        ]);
        
        $contact = Contact::findOrFail($id);
        $contact->update(['status' => $request->status]);
        
        return redirect()
            ->back()
            ->with('success', 'Status pesan berhasil diupdate');
    }

    /**
     * Remove the specified contact.
     */
    public function destroy($id)
    {
        $contact = Contact::findOrFail($id);
        $contact->delete();
        
        return redirect()
            ->route('admin.contacts.index')
            ->with('success', 'Pesan berhasil dihapus');
    }

    /**
     * Bulk delete contacts.
     */
    public function bulkDestroy(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:contacts,id'
        ]);
        
        Contact::whereIn('id', $request->ids)->delete();
        
        return redirect()
            ->route('admin.contacts.index')
            ->with('success', count($request->ids) . ' pesan berhasil dihapus');
    }

    /**
     * Export contacts to CSV.
     */
    public function export(Request $request)
    {
        $query = Contact::query();
        
        if ($request->has('status') && $request->status != 'all') {
            $query->where('status', $request->status);
        }
        
        $contacts = $query->orderBy('created_at', 'desc')->get();
        
        $filename = 'contacts_' . date('Y-m-d_His') . '.csv';
        $handle = fopen('php://temp', 'w+');
        
        // Add headers
        fputcsv($handle, [
            'ID', 'Nama', 'Email', 'Subjek', 'Pesan', 
            'Status', 'Dibaca Pada', 'Dibalas Pada', 'Dibuat Pada'
        ]);
        
        // Add data
        foreach ($contacts as $contact) {
            fputcsv($handle, [
                $contact->id,
                $contact->name,
                $contact->email,
                $contact->subject,
                $contact->message,
                $contact->status,
                $contact->read_at,
                $contact->replied_at,
                $contact->created_at
            ]);
        }
        
        rewind($handle);
        $csv = stream_get_contents($handle);
        fclose($handle);
        
        return response($csv)
            ->header('Content-Type', 'text/csv')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
    }
}