<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Events\LogAction;
use App\Models\Config;
use App\Models\ConfigHostel;
use App\Models\Contract;
use App\Models\ContractAttachment;
use App\Models\Hostel;
use App\Models\Renter;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\Html;

class ContractController extends BaseController
{
    //
    /**
     * @api {post} /delete-attachment Xóa file đính kèm khỏi HĐ
     * @apiName delete-attachment
     * @apiGroup Contract
     * @apiDescription Api Xóa file đính kèm khỏi HĐ
     * @apiParam {String} contract_id
     * @apiParam {String} attachment_id
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function deleteAttachment(Request $request)
    {
        $contractId = $request->input('contract_id');
        $attachmentId = $request->input('attachment_id');

        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        ContractAttachment::query()->where('id', $attachmentId)
            ->where('contract_id', $contractId)
            ->delete();
        $user = Functions::getCurrentUser();

        $desc = '{' . $user->name . '} đã xóa đính kèm file hợp đồng khách {' . $contract->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
        if ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            $desc = '{' . $user->name . '} đã xóa đính kèm file hợp đồng khách {' . $contract->name . '} giường {' . optional($contract->bed)->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
        }
        event(new LogAction([
            'type' => 'delete-contract-attachment',
            'user_id' => optional($user)->id,
            'object_id' => $attachmentId,
            'hostel_id' => $contract->hostel_id,
            'room_id' => $contract->room_id,
            'desc' => $desc
        ]));

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    /**
     * @api {get} /view-contract Xem hợp đồng HTML / Tải HĐ
     * @apiName view-contract
     * @apiGroup Contract
     * @apiDescription Xem hợp đồng HTML
     * @apiParam {String} contract_id
     * @apiParam {String} type Nếu type là download data sẽ là url để truy cập vào đó sẽ tải xuống HĐ. Nếu ko data sẽ là HTML hợp đồng
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

    public function viewContract(Request $request)
    {
        $contractId = $request->input('contract_id');
        $type = $request->input('type');
        $contract = Contract::find($contractId);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $ownerId = $this->user->id;
        if ($this->user->type == User::STAFF) {
            $ownerId = $this->user->staff_owner_id;
        } else if ($this->user->type == User::RENTER) {
            $ownerId = $contract->hostel->owner_id;
        }
        $config = Config::query()->where('owner_id', $ownerId)->first();
        $contractTemplate = null;
        if ($config) {
            $contractTemplate = $config->contract;
        }

        $configHostel = ConfigHostel::query()
            ->where('owner_id', $ownerId)
            ->where('hostel_id', $contract->hostel_id)
            ->first();

        if ($configHostel) {
            if (!empty(optional($configHostel)->contract)) {
                $contractTemplate = $configHostel->contract;
            }
        }

        $renter = Renter::query()->where('user_id', $contract->renter_id)->first();
        if ($type == 'download') {
            $isDownload = true;
            $contractTemplate = Functions::getContractTemplate($contract, $contractTemplate, $renter, true);;
            $contractTemplate = html_entity_decode($contractTemplate);
            $contractTemplate = preg_replace('/&(?!#?[a-z0-9]+;)/', '-', $contractTemplate);
            $phpWord = new PhpWord();
            $section = $phpWord->addSection();
            Html::addHtml($section, $contractTemplate);
            $dirName = 'hop-dong/hostel-' . $contract->hostel->id . '/room-' . $contract->room->id;
            $objectWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
            if (!\File::exists(public_path($dirName))) {
                \File::makeDirectory(public_path($dirName), 0777, true);
            }

            if (\File::exists(public_path($dirName . '/phong-' . str_slug($contract->room->name) . '-nha-tro-' . str_slug($contract->hostel->name) . '.docx'))) {
                \File::delete(public_path($dirName . '/phong-' . str_slug($contract->room->name) . '-nha-tro-' . str_slug($contract->hostel->name) . '.docx'));
            }

            $objectWriter->save(public_path($dirName . '/phong-' . str_slug($contract->room->name) . '-nha-tro-' . str_slug($contract->hostel->name) . '.docx'));

            return response([
                'status' => 1,
                'data' => url('/' . $dirName . '/phong-' . str_slug($contract->room->name) . '-nha-tro-' . str_slug($contract->hostel->name) . '.docx')
            ]);
        }
        $contractTemplate = Functions::getContractTemplate($contract, $contractTemplate, $renter);

        return response([
            'status' => 1,
            'data' => $contractTemplate
        ]);
    }


    /**
     * @api {get} /preview-contract Preview HD
     * @apiName preview-contract
     * @apiGroup Contract
     * @apiDescription Api Preview HD
     * @apiParam {String} hostel_id
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function previewContract(Request $request)
    {
        $data = $request->all();
        $ownerId = $this->user->id;
        if ($this->user->type == User::STAFF) {
            $ownerId = $this->user->staff_owner_id;
        }
        $config = Config::query()
            ->where('owner_id', $ownerId)
            ->first();
        $contractTemplate = null;
        if ($config) {
            $contractTemplate = $config->contract;
        }

        $configHostel = ConfigHostel::query()
            ->where('owner_id', $ownerId)
            ->where('hostel_id', $data['hostel_id'])
            ->first();

        if ($configHostel) {
            if (!empty(optional($configHostel)->contract)) {
                $contractTemplate = $configHostel->contract;
            }
        }
        return response([
            'status' => 1,
            'data' => $contractTemplate
        ]);
    }
}
