<?php

namespace App\Service;

use App\Config\Main;
use App\Core\Service\Logger;
use Exception;

class AttachmentUploader
{
    public function processAttachments($files,$data,$user_data)
    {
        try {
            $attachment_list = [];
            if (!empty($files['attachments'])) {
                $uploadDir = Main::getUploadPath();
                $uploadFolder = Main::getUploadFolder();
                if($data['master_name'] == 'order_attachments'){
                    $data['master_name'] = $data['master_name'].'/order-' . $data['ref_id'];
                }
                $uploadBasePath = $uploadDir . '/comp-' . $user_data->comp_id . '/'. $data['master_name'] . '/';
                if (!is_dir($uploadBasePath)) {
                    mkdir($uploadBasePath, 0777, true);
                }
                if (!is_dir($uploadBasePath)) {
                    throw new \Exception("Upload path does not exist");
                }

                $max_file_size = Main::getUploadMaxSize();
                // $allowed_file_types = Main::getAllowedLogoFileTypes();
                foreach ($files['attachments']['name'] as $i => $name) {
                    if ($files['attachments']['size'][$i] > Main::getUploadMaxSize()) {
                        throw new \Exception('File size should be less than ' . ($max_file_size / 1024) . ' KB');
                    }
                    // if (!in_array($files['attachments']["type"][$i], $allowed_file_types)) {
                    //     throw new \Exception('Invalid file type found in attachment list. Valid file types are:' . implode(", ", $allowed_file_types));
                    // }
                    $file_name = 'attachment' . '_' . time() . '_' . rand(10,99) . '.' . pathinfo($name, PATHINFO_EXTENSION);
                    if (!move_uploaded_file($files['attachments']['tmp_name'][$i], $uploadBasePath . $file_name)) {
                        throw new \Exception("Error in uploading attachment file:" . $name);
                    }
                    $file_path = $uploadFolder . '/comp-' . $user_data->comp_id . '/' . $data['master_name'] . '/' .$file_name;
                    $attachment_list[] = [
                        "path" => $file_path,
                        "name" => $name,
                        "size" => $files['attachments']["size"][$i],
                        "type" => $files['attachments']["type"][$i]
                    ];
                }
                return ["status" => true, "attachment_list" => $attachment_list];
            }else{
                throw new Exception('Please Select Attachment');
            }
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            return ["status" => false, "error" => $e->getMessage()];
        }
    }
}
