<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ProductInquiry;
use Illuminate\Support\Facades\Auth;

class UserInquiryController extends Controller
{
    /**
     * Display a listing of user's inquiries
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        $email = $user->email;

        // Get inquiries based on user's email
        $query = ProductInquiry::with('product')
            ->where('email', $email)
            ->orderByDesc('created_at');

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('message', 'like', "%{$search}%")
                  ->orWhereHas('product', function($productQuery) use ($search) {
                      $productQuery->where('product_title', 'like', "%{$search}%");
                  });
            });
        }

        // Filter by read/unread status
        if ($request->filled('status')) {
            if ($request->status === 'unread') {
                $query->where('is_read', false);
            } elseif ($request->status === 'read') {
                $query->where('is_read', true);
            }
        }

        $inquiries = $query->paginate(10)->withQueryString();

        return view('user.inquiries.index', compact('inquiries'));
    }

    /**
     * Display the specified inquiry
     */
    public function show($id)
    {
        try {
            $user = Auth::user();
            
            if (!$user) {
                abort(401, 'Silakan login terlebih dahulu.');
            }
            
            $email = $user->email;
            
            // Find inquiry and check authorization
            $inquiry = ProductInquiry::with('product')
                ->where('id', $id)
                ->where('email', $email)
                ->first();
            
            if (!$inquiry) {
                // Check if inquiry exists but belongs to different user
                $exists = ProductInquiry::where('id', $id)->exists();
                if ($exists) {
                    abort(403, 'Anda tidak memiliki akses ke penawaran produk ini.');
                }
                abort(404, 'Penawaran produk tidak ditemukan.');
            }

            // Jangan update is_read di sini!
            // is_read hanya untuk admin, bukan untuk user
            // User hanya melihat status apakah admin sudah membaca atau belum

            return view('user.inquiries.show', compact('inquiry'));
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            abort(404, 'Penawaran produk tidak ditemukan.');
        } catch (\Exception $e) {
            \Log::error('Error in UserInquiryController@show: ' . $e->getMessage());
            abort(500, 'Terjadi kesalahan saat memuat data.');
        }
    }
}

