<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class ComplaintController extends Controller
{
    // GET /api/complaints
    public function index(Request $request)
    {
        $user = Auth::user();
        if (!$user || !$user->society_id) {
            return response()->json(['status' => 'error', 'message' => 'Unauthorized'], 403);
        }

        $query = DB::table('complaints')
            ->leftJoin('users as creator', 'complaints.user_id', '=', 'creator.id')
            ->leftJoin('users as assignee', 'complaints.assigned_to', '=', 'assignee.id')
            ->select('complaints.*', 'creator.name as creator_name', 'assignee.name as assignee_name')
            ->where('complaints.society_id', $user->society_id);

        // Role restriction: Members only see their own
        $isAdmin = in_array($user->role, ['society_admin', 'secretary', 'super_admin', 'employee']);
        if (!$isAdmin) {
            $query->where('complaints.user_id', $user->id);
        }

        // Filters
        if ($request->has('status'))
            $query->where('complaints.status', $request->status);
        if ($request->has('priority'))
            $query->where('complaints.priority', $request->priority);
        if ($request->has('search')) {
            $s = $request->search;
            $query->where(function ($q) use ($s) {
                $q->where('complaints.subject', 'like', "%{$s}%")
                    ->orWhere('complaints.description', 'like', "%{$s}%")
                    ->orWhere('complaints.id', 'like', "%{$s}%"); // For Ticket ID search
            });
        }

        $complaints = $query->orderBy('complaints.created_at', 'desc')->paginate(10);

        return response()->json($complaints);
    }

    // POST /api/complaints
    public function store(Request $request)
    {
        $user = Auth::user();

        $validator = Validator::make($request->all(), [
            'subject' => 'required|string|max:255',
            'description' => 'required|string',
            'category' => 'required|in:maintenance,security,parking,billing,cleaning,other',
            'priority' => 'required|in:low,medium,high,critical',
            'attachment' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:5120'
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'message' => 'Validation failed', 'errors' => $validator->errors()], 422);
        }

        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('complaints', 'public');
        }

        $id = DB::table('complaints')->insertGetId([
            'society_id' => $user->society_id,
            'user_id' => $user->id,
            'subject' => $request->subject,
            'description' => $request->description,
            'category' => $request->category,
            'priority' => $request->priority,
            'status' => 'open',
            'attachment' => $attachmentPath,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        return response()->json(['status' => 'success', 'message' => 'Complaint registered successfully', 'id' => $id], 201);
    }

    // GET /api/complaints/{id}
    public function show($id)
    {
        $user = Auth::user();
        $query = DB::table('complaints')
            ->leftJoin('users as creator', 'complaints.user_id', '=', 'creator.id')
            ->leftJoin('users as assignee', 'complaints.assigned_to', '=', 'assignee.id')
            ->select('complaints.*', 'creator.name as creator_name', 'creator.phone as creator_phone', 'creator.email as creator_email', 'assignee.name as assignee_name')
            ->where('complaints.id', $id)
            ->where('complaints.society_id', $user->society_id);

        $isAdmin = in_array($user->role, ['society_admin', 'secretary', 'super_admin', 'employee']);
        if (!$isAdmin) {
            $query->where('complaints.user_id', $user->id);
        }

        $complaint = $query->first();

        if (!$complaint) {
            return response()->json(['status' => 'error', 'message' => 'Complaint not found'], 404);
        }

        return response()->json($complaint);
    }

    // PUT /api/complaints/{id}
    public function update(Request $request, $id)
    {
        $user = Auth::user();
        $isAdmin = in_array($user->role, ['society_admin', 'secretary', 'super_admin', 'employee']);

        $complaint = DB::table('complaints')->where('id', $id)->where('society_id', $user->society_id)->first();
        if (!$complaint)
            return response()->json(['status' => 'error', 'message' => 'Not found'], 404);

        if (!$isAdmin && $complaint->user_id !== $user->id) {
            return response()->json(['status' => 'error', 'message' => 'Unauthorized'], 403);
        }

        // Logic split: Admin can update Status/Assign/Notes. Member can maybe Cancel? 
        // For MVP, if member, only allow cancelling if open?
        // Admin updates:
        $updates = [];

        if ($isAdmin) {
            if ($request->has('status'))
                $updates['status'] = $request->status;
            if ($request->has('assigned_to'))
                $updates['assigned_to'] = $request->assigned_to;
            if ($request->has('resolution_notes'))
                $updates['resolution_notes'] = $request->resolution_notes;

            if ($request->status === 'resolved' && $complaint->status !== 'resolved') {
                $updates['resolved_at'] = now();
            }
            if ($request->status === 'closed' && $complaint->status !== 'closed') {
                $updates['closed_at'] = now();
            }
        }

        $updates['updated_at'] = now();

        DB::table('complaints')->where('id', $id)->update($updates);

        return response()->json(['status' => 'success', 'message' => 'Complaint updated']);
    }

    // GET /api/complaints/{id}/download
    public function downloadAttachment($id)
    {
        $user = Auth::user();
        $complaint = DB::table('complaints')->where('id', $id)->where('society_id', $user->society_id)->first();

        // Check permission...
        $isAdmin = in_array($user->role, ['society_admin', 'secretary', 'super_admin', 'employee']);
        if (!$complaint || (!$isAdmin && $complaint->user_id !== $user->id)) {
            return response()->json(['status' => 'error', 'message' => 'Unauthorized or Not Found'], 404);
        }

        if (!$complaint->attachment) {
            return response()->json(['status' => 'error', 'message' => 'File not found'], 404);
        }

        $filePath = storage_path('app/public/' . $complaint->attachment);
        if (!file_exists($filePath)) {
            return response()->json(['status' => 'error', 'message' => 'File missing from server'], 404);
        }

        $headers = [
            'Content-Type' => mime_content_type($filePath),
            'Content-Disposition' => 'inline; filename="' . basename($filePath) . '"',
        ];

        return response(file_get_contents($filePath), 200, $headers);
    }
}
