<template>
    <Modal
        ref="modal"
        size="2xl"
        @closed="null"
        :title="$t('Register.pay_before_start')"
        color="blue"
    >
        <FormKit
            :actions="false"
            name="pay_service"
            type="form"
            @submit="submit"
        >
            <div class="container flex flex-col gap-5 p-5">
                <ul class="flex flex-col w-full gap-4">
                    <li class="flex flex-col w-full gap-4">
                        <p class="font-semibold">{{$t('Register.payment_details') }}</p>

                        <span
                            class="flex items-center justify-between w-full text-sm font-medium text-gray-200"
                        >
                            <span
                                >{{$t('Register.project_amount_in') }} {{ activeCurrency() }}:</span
                            >
                            <span
                                >{{ currency(milestone.amount) }} ({{$t('Register.you_will_be_billed') }})</span
                            >
                        </span>
                        <span
                            class="flex items-center justify-between w-full text-sm font-medium text-gray-200"
                        >
                            <span>{{$t('Register.project_amount_in') }} USD:</span>
                            <span>{{ currency(milestone.amount, "USD") }}</span>
                        </span>
                    </li>
                    <li class="border-b border-b-blue-200"></li>
                    <li class="flex items-center justify-between">
                        <Switch
                            :label="`Muhandisin wallet (Balance: ${currency(
                                $page.props.current_user.wallet.available_funds,
                                'USD'
                            )})`"
                            v-model:enabled="form.use_wallet"
                        />
                    </li>
                    <li
                        class="flex flex-col w-full gap-4 p-4 bg-gray-300 rounded-lg"
                    >
                        <p class="font-semibold text-white">{{ $t('Register.order_details') }}</p>
                        <span
                            class="flex items-center justify-between w-full text-sm font-medium text-gray-200"
                        >
                            <span>{{$t('Register.pay_by_card') }}</span>
                            <span>{{ currency(milestone.amount, "USD") }}</span>
                        </span>
                        <span
                            v-if="form.use_wallet"
                            class="flex items-center justify-between w-full text-sm font-medium text-gray-200"
                        >
                            <span>{{$t('Register.muhandisin_wallet') }}</span>
                            <span
                                >-{{ currency(muhandisinWallet, "USD") }}</span
                            >
                        </span>
                        <span
                            class="flex items-center justify-between w-full text-xs font-medium text-gray-200"
                        >
                            <span>{{$t('Register.vat') }}</span>
                            <span>({{$t('Register.included') }})</span>
                        </span>
                        <span class="border-b border-b-white"></span>
                        <span
                            class="flex items-center justify-between w-full text-sm font-medium text-white"
                        >
                            <span>{{$t('Register.total') }}:</span>
                            <span>{{ currency(calculatedTotal, "USD") }}</span>
                        </span>
                    </li>
                    <li>
                        <FormKit
                            name="accepted_terms"
                            :classes="{
                                label:
                                    'text-xs ' +
                                    (form.accepted
                                        ? 'text-blue-300'
                                        : 'text-gray-200'),
                            }"
                            :label="$t('Register.by_continuing')"
                            type="checkbox"
                            v-model="form.accepted"
                        ></FormKit>
                    </li>
                </ul>

                <div class="flex justify-end w-full">
                    <Button
                        :disabled="form.processing || !form.accepted"
                        :loading="form.processing"
                        @click="openConfirm"
                        size="md"
                        >{{ $t('Register.confirm') }}</Button
                    >
                </div>
            </div>
        </FormKit>
    </Modal>
    <Modal
        ref="signature_modal"
        size="lg"
        @closed="null"
        :title="$t('Register.confirm_payment')"
        color="blue"
    >
        <FormKit :actions="false" name="payment" type="form" @submit="submit">
            <FormKit name="proposal_payment" type="group">
                <template #default="{ state: { valid } }">
                    <div class="container flex flex-col gap-5 p-5">
                        <div
                            id="proposal-payment-confirm"
                            class="flex flex-col gap-5 p-1 bg-blue-100"
                        >
                            <div
                                v-if="proposal.milestones.length > 1"
                                class="p-4 bg-blue-200 rounded-md"
                            >
                                <div class="flex">
                                    <div class="flex-shrink-0">
                                        <svg
                                            class="w-5 h-5 text-blue-300"
                                            viewBox="0 0 20 20"
                                            fill="currentColor"
                                            aria-hidden="true"
                                        >
                                            <path
                                                fill-rule="evenodd"
                                                d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z"
                                                clip-rule="evenodd"
                                            ></path>
                                        </svg>
                                    </div>
                                    <div class="ml-3">
                                        <h3
                                            class="text-sm font-medium text-blue-300"
                                        >
                                            {{ $t('Register.attention') }}
                                        </h3>
                                        <div
                                            class="mt-2 text-sm text-blue-300/75"
                                        >
                                            <p>
                                                {{ $t('Register.attention_text') }}
                                            </p>
                                            <br />
                                            <p>
                                                {{ $t('Register.attention_text2') }}
                                                <b>
                                                    {{ $t('Register.attention_text3') }}
                                                    {{
                                                        currency(
                                                            sumOfMilestones,
                                                            "USD"
                                                        )
                                                    }}.
                                                </b>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <ul class="muh-form-group">
                                <li>
                                    <FormKit
                                        v-model="milestone.amount"
                                        :classes="{
                                            outer: 'mb-0',
                                            inner: 'bg-blue-100 opacity-50 cursor-not-allowed',
                                            input: 'bg-blue-100',
                                            help: 'text-2xs',
                                        }"
                                        :help="$t('Register.amount_to_pay_help')"
                                        :label="$t('Register.amount_to_pay')"
                                        name="milestone_amount"
                                        type="number"
                                        disabled
                                    >
                                        <template #suffix>
                                            <span
                                                class="text-[10px] text-gray-200 select-none px-0.5"
                                            >
                                                USD
                                            </span>
                                        </template>
                                    </FormKit>
                                </li>
                                <li>
                                    <FormKit
                                        v-model="form.client_signature"
                                        :classes="{
                                            outer: 'mb-0',
                                            help: 'text-2xs',
                                        }"
                                        :label="$t('Register.signture')"
                :help="$t('Register.signture_help')"                                        name="client_signature"
                                        type="text"
                                        validation="required|string|length:3,255"
                                        required
                                    >
                                    </FormKit>
                                </li>
                            </ul>
                            <div
                                class="flex justify-start items-center gap-2.5 w-full"
                            >
                                <div
                                    class="flex-1 p-2.5 flex-col flex gap-1 bg-gradient-to-br from-[#414141] to-[#222222] rounded-lg"
                                >
                                    <span class="text-xs text-gray-200"
                                        >{{ $t('Register.agreed') }}:</span
                                    >
                                    <span
                                        class="text-sm text-blue-100 line-clamp-1"
                                        >{{
                                            currency(sumOfMilestones, "USD")
                                        }}</span
                                    >
                                </div>
                                <div
                                    class="flex-1 p-2.5 flex-col flex gap-1 bg-gradient-to-br from-[#414141] to-[#222222] rounded-lg"
                                >
                                    <span class="text-xs text-gray-200"
                                        >To be paid:</span
                                    >
                                    <span
                                        class="text-sm text-blue-100 line-clamp-1"
                                        >{{
                                            currency(milestone.amount, "USD")
                                        }}</span
                                    >
                                </div>
                                <div
                                    class="flex-1 p-2.5 flex-col flex gap-1 bg-gradient-to-br from-[#414141] to-[#222222] rounded-lg"
                                >
                                    <span class="text-xs text-gray-200"
                                        >{{ $t('Register.remaining') }}:</span
                                    >
                                    <span
                                        class="text-sm text-blue-100 line-clamp-1"
                                        >{{ currency(remaining, "USD") }}</span
                                    >
                                </div>
                            </div>
                        </div>
                        <div class="flex justify-end w-full">
                            <Button
                                :disabled="form.processing || !valid"
                                :loading="form.processing"
                                size="md"
                                @click="submit"
                                >{{ $t('Register.pay_securely') }}</Button
                            >
                        </div>
                    </div>
                </template>
            </FormKit>
        </FormKit>
    </Modal>
</template>

<script>
import Modal from "@/components/General/FormModal";
import Card from "@/components/Containers/ContentCard";
import { Link } from "@inertiajs/inertia-vue3";
import Button from "@/Jetstream/Button";
import { useForm } from "@inertiajs/inertia-vue3";
import Switch from "@/components/Inputs/Switch.vue";

export default {
    props: {
        proposal: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            form: useForm({
                client_signature: "",
                use_wallet: false,
                accepted: false,
            }),
        };
    },
    computed: {
        milestone() {
            return this.proposal.milestones[0];
        },
        sumOfMilestones() {
            return this.proposal.milestones.reduce(
                (sum, milestone) => sum + milestone.amount,
                0
            );
        },
        agreed() {
            const durationFactor =
                this.project.rate_type == "daily"
                    ? 1
                    : this.project.rate_type == "monthly"
                    ? 30
                    : this.project.rate_type == "yearly"
                    ? 365
                    : 1;

            const factor =
                this.project.budget_type == "Rate"
                    ? this.form.duration / durationFactor
                    : 1;

            let total = this.proposal.amount;

            return (total * factor).toFixed(2);

            return this.proposal.project.budget_type === "Rate"
                ? this.proposal.amount * this.milestone.duration
                : this.proposal.amount;
        },
        remaining() {
            return this.sumOfMilestones - this.milestone.amount;
        },
        muhandisinWallet() {
            if (
                this.$page.props.current_user.wallet.available_funds >=
                this.milestone.amount
            )
                return this.milestone.amount;
            else return this.$page.props.current_user.wallet.available_funds;
        },
        calculatedTotal() {
            if (this.form.use_wallet)
                return this.milestone.amount - this.muhandisinWallet;
            return this.milestone.amount;
        },
    },
    methods: {
        open() {
            this.$refs.modal.open();
        },
        close() {
            this.$refs.modal.close();
            this.closeConfirm();
        },
        submit() {
            let signature = null;
            this.domtoimage
                .toPng(document.getElementById("proposal-payment-confirm"))
                .then(function (dataUrl) {
                    // turn blob into image

                    signature = dataUrl;
                })
                .finally(() => {
                    this.form
                        .transform((data) => ({
                            client_signature: signature,
                            use_wallet: this.form.use_wallet,
                        }))
                        .post(
                            route(
                                "payment.milestone.payment-form.show",
                                this.milestone.id
                            ),
                            {
                                preserveScroll: true,
                                onSuccess: () => {
                                    this.close();
                                    this.$emit("close");
                                },
                                onError: (err) => {
                                    console.log(err);
                                },
                            }
                        );
                });
        },
        openConfirm() {
            this.$refs.signature_modal.open();
        },
        closeConfirm() {
            this.$refs.signature_modal.close();
        },
    },
    components: {
        Modal,
        Card,
        Button,
        Link,
        Switch,
    },
    mounted() {},
};
</script>

<style>
.muh-form-group {
    display: flex;
    flex-direction: column;
    gap: 10px;
    width: 100%;
}

.muh-form-group > li {
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
}

.muh-form-group > li:focus-within {
    @apply border border-blue-100;
}

.formkit-form {
    width: 100%;
    flex: 1 1 0%;
}
</style>
