<?php

namespace Booktics\Models;

use Booktics\Abstracts\Booktics_Database;
use Booktics\Abstracts\Model;

class Guest_Model extends Model {

    protected $table = 'booktics_guests';
    protected $fillable = array(
        'id',
        'wp_user_id',
        'name',
        'user_login',
        'email',
        'phone',
        'description',
        'status',
        'image',
        'created_at',
        'updated_at',
    );

    /**
     * Get virtual attributes for the guest model
     *
     * @param object $row
     *
     * @return array
     */
    protected function get_virtual_attributes( object $row ): array {
        if ( ! $row ) {
            return array();
        }

        $db = new Booktics_Database();

        $total_booking = ( new Order_Model( $db ) )->count( array( 'customer_id' => $row->id ) );
        $total_amount  = ( new Order_Model( $db ) )->sum( 'total', array( 'customer_id' => $row->id ) );

        $orders  = ( new Order_Model( $db ) )->get( array( 'customer_id' => $row->id ) );

        // Remove canceled appointment costs from total amount for each customer
        if ( isset( $orders['items'] ) && is_array( $orders['items'] ) ) {
            foreach ( $orders['items'] as $order ) {
                $appointments = (new Appointment_Model())->where('order_id', $order->id);

                if ( ! isset( $appointments ) || ! is_array( $appointments )) {
                    continue;
                }

                foreach ( $appointments as $appointment) {
                    if ( $appointment->status === 'canceled' ) {
                        $total_amount  -= $order->total;
                        $total_booking -= 1;
                        break;
                    }
                }
            }
        }

        return array(
            'status_label' => ( $row->status == 1 ) ? 'Active' : 'Deactive',
            'total_booking' => $total_booking,
            'total_amount' => $total_amount,
            'user_registered' => gmdate( 'd M Y h:iA', strtotime( $row->created_at ) ),
        );
    }
}
