<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RecordAttachment;
use App\Models\VesselRecord;
use Illuminate\Support\Facades\Storage;

class AttachmentController extends Controller
{
    public function store(Request $request, VesselRecord $vesselRecord)
    {
        $request->validate([
            'attachments.*' => 'required|file|max:10240|mimes:pdf,doc,docx,xls,xlsx,jpg,jpeg,png,txt'
        ]);

        $uploadedFiles = [];

        if ($request->hasFile('attachments')) {
            foreach ($request->file('attachments') as $file) {
                $originalName = $file->getClientOriginalName();
                $filename = time() . '_' . $originalName;

                // Store file in public/uploads directory
                $path = $file->storeAs('uploads', $filename, 'public');

                // Create attachment record
                $attachment = RecordAttachment::create([
                    'record_id' => $vesselRecord->id,
                    'file_name' => $originalName,
                    'file_path' => $filename,
                    'uploaded_at' => now()
                ]);

                $uploadedFiles[] = $attachment;
            }
        }

        return response()->json([
            'success' => true,
            'message' => count($uploadedFiles) . ' file(s) uploaded successfully',
            'files' => $uploadedFiles
        ]);
    }

    public function download(RecordAttachment $attachment)
    {
        // Check if attachment exists
        if (!$attachment->exists) {
            abort(404, 'Attachment not found');
        }

        $filePath = public_path('uploads/' . $attachment->file_path);

        if (!file_exists($filePath)) {
            // Log the missing file for debugging
            \Log::warning('Missing attachment file', [
                'attachment_id' => $attachment->id,
                'file_path' => $attachment->file_path,
                'file_name' => $attachment->file_name,
                'record_id' => $attachment->record_id
            ]);

            return redirect()->back()->with('error', 'File "' . $attachment->file_name . '" not found on server. The file may have been moved or deleted.');
        }

        return response()->download($filePath, $attachment->file_name);
    }

    public function preview(RecordAttachment $attachment)
    {
        // Check if attachment exists
        if (!$attachment->exists) {
            abort(404, 'Attachment not found');
        }

        $filePath = public_path('uploads/' . $attachment->file_path);

        if (!file_exists($filePath)) {
            // Log the missing file for debugging
            \Log::warning('Missing attachment file for preview', [
                'attachment_id' => $attachment->id,
                'file_path' => $attachment->file_path,
                'file_name' => $attachment->file_name,
                'record_id' => $attachment->record_id
            ]);

            abort(404, 'File "' . $attachment->file_name . '" not found on server. The file may have been moved or deleted.');
        }

        // Get file extension to determine content type
        $extension = strtolower(pathinfo($attachment->file_name, PATHINFO_EXTENSION));

        // Set appropriate content type
        $contentType = match($extension) {
            'pdf' => 'application/pdf',
            'jpg', 'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'txt' => 'text/plain',
            'doc' => 'application/msword',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'xls' => 'application/vnd.ms-excel',
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            default => 'application/octet-stream'
        };

        // For images and PDFs, display inline. For others, force download
        $disposition = in_array($extension, ['pdf', 'jpg', 'jpeg', 'png', 'txt']) ? 'inline' : 'attachment';

        return response()->file($filePath, [
            'Content-Type' => $contentType,
            'Content-Disposition' => $disposition . '; filename="' . $attachment->file_name . '"'
        ]);
    }

    public function destroy(RecordAttachment $attachment)
    {
        // Delete file from storage
        $filePath = 'uploads/' . $attachment->file_path;
        if (Storage::disk('public')->exists($filePath)) {
            Storage::disk('public')->delete($filePath);
        }

        // Delete attachment record
        $attachment->delete();

        return response()->json([
            'success' => true,
            'message' => 'File deleted successfully'
        ]);
    }
}
