<?php

namespace App\Http\Controllers;

use App\Http\Requests\AttachmentStoreRequest;
use App\Models\Mailbox;
use App\Models\MailboxAttachment;
use App\Services\MailBoxService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class MailboxAttachmentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function pendingAttachmentEntry()
    {
        $mails = Mailbox::with('client')
            ->select('mailboxes.*', 'address_books.name as address_book_name', 'mailbox_attachments.attachment')
            ->leftJoin('address_books', 'mailboxes.mail_from', '=', 'address_books.id')
            ->leftJoin('mailbox_attachments', 'mailboxes.id', '=', 'mailbox_attachments.mailbox_id')
            ->where('mailboxes.scan_permission', 1)
            ->whereNull('mailboxes.is_scanned')
            ->whereNotNull('mailboxes.scan_permission_at')
            ->orderBy('mailboxes.scan_permission_at', 'asc')
            ->get();


        return view('app.mailbox.attachment-entry-list', compact('mails'));
    }


    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function uploadMailAttachment(AttachmentStoreRequest $request, MailBoxService $mailBoxService)
    {
        $att_exist = MailboxAttachment::where('mailbox_id', $request->mail_id)->first();
        if ($att_exist) {
            return errorResponse('Attachment already exists');
        }

        try {
            $mail = Mailbox::where('id', $request->mail_id)->first();
            $path = 'mailbox/' . now()->format('Y');
            $attachment = fileUpload($request->attachment, $path);
            $attachment_title = $mail->client_id . '_' . $mail->mail_id . '.' . $request->attachment->getClientOriginalExtension();

            MailboxAttachment::create([
                'mailbox_id' => $request->mail_id,
                'attachment' => $path . '/' . $attachment,
                'attachment_title' => $attachment_title
            ]);

            $mail->update(['is_scanned' => now()]);
        } catch (\Exception $e) {
            return errorResponse('Something went wrong, please try again', 500, $e->getMessage());
        }


        return successResponse('Attachment uploaded successfully');
    }

    /**
     * Display the specified resource.
     */
    public function show(MailboxAttachment $mailboxAttachment)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(MailboxAttachment $mailboxAttachment)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, MailboxAttachment $mailboxAttachment)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(MailboxAttachment $mailboxAttachment)
    {
        //
    }

    public function downloadAttachment($id)
    {
        $attachment = MailboxAttachment::with('mailbox')->where('attachment', 'like', '%' . $id . '%')->first();


        $attachmentPath = public_path('storage/uploads/' . $attachment->attachment);

        if (!file_exists($attachmentPath)) {
            return "Attachment not found. Click <a href='/app'>here</a> to go back";
        }

        if (
            (Auth::user()->role_id == 1 && $attachment->mailbox->user_type_id == Auth::user()->id) ||
            Auth::user()->user_type_id != 1
        ) {
            return response()->download($attachmentPath);
        }

        return "You are not authorized to download this attachment. Click <a href='/app'>here</a> to go back";
    }
}
