<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Landingpage extends App_Controller
{

    public $selectedThemeDetails = 'default';

    public function __construct()
    {
        hooks()->do_action('after_clients_area_init', $this);

        parent::__construct();

        $selectedTheme = get_option('propertybase_active_theme') ?: 'default';
        $themeDetails = propertybase_get_landing_page_details($selectedTheme);
        $isLandingDisabled = get_option('propertybase_disable_properties_landing_page');

        if ($isLandingDisabled) {
            die('Landing page is disabled, you can activate it from admin or <a target="_blank" href="https://lenzcreative.net">contact us</a> for help.');
        }

        if (empty($themeDetails) || is_null($themeDetails)) {
            die('The selected template is not properly configured. Please <a target="_blank" href="https://lenzcreative.net">contact us</a> or activate the default template.');
        }

        if (!isset($themeDetails['theme_index_path']) || $themeDetails['theme_index_path'] == '') {
            die('The template must have an index file specified. Please review the configuration or <a target="_blank" href="https://lenzcreative.net">contact us</a>.');
        }

        $this->load->model('PropertyLandingpage_model');
        $this->selectedThemeDetails = $themeDetails;
    }

    public function index()
    {
        $data = [];

        $this->load->model('propertybase_model');
        $this->load->model('propertycategories_model');
        $this->load->model('PropertyOwnershipTypes_model');

        $filters = [
            'category' => $this->input->get('category', true),
            'country' => $this->input->get('country', true),
            'property_purpose' => $this->input->get('property_purpose', true),
            'ownership' => $this->input->get('ownership', true),
        ];

        $filters = array_filter($filters, function ($value) {
            return !empty($value);
        });

        $defaultConditions = [
            'is_visible_for_public' => 1,
            'is_enabled' => 1
        ];

        if (get_option('propertybase_hide_rented_and_sold_properties_from_listing') == '1') {
            $defaultConditions['property_status'] = 1;
        }

        $data['properties_list'] = propertybase_fetch_properties(array_merge($defaultConditions, $filters));

        $data['property_categories'] = $this->propertycategories_model->get_all();
        $data['property_ownership_types'] = $this->PropertyOwnershipTypes_model->get_all();

        $data = hooks()->apply_filters('propertybase_landingpage_index_data', $data);

        propertybase_load_view($this->selectedThemeDetails['theme_index_path'], $data);
    }

    public function property($property_id)
    {
        if (!isset($this->selectedThemeDetails['theme_property_path']) || $this->selectedThemeDetails['theme_property_path'] == '') {
            die('The template must have a single property file specified. Please review the configuration or <a target="_blank" href="https://lenzcreative.net">contact us</a>.');
        }

        $data = [];

        $data['title'] = propertybase_formatted_property_name($property_id);

        $this->load->model('propertybase_model');

        $this->propertybase_model->update($property_id, ['total_views' => 1]);

        $data['property_data'] = $this->propertybase_model->get($property_id);

        $data['property_main_image'] = $this->propertybase_model->get_property_main_image_attachment($property_id);
        $data['property_floor_image'] = $this->propertybase_model->get_property_floor_image_attachment($property_id);
        $data['property_list_images'] = $this->propertybase_model->get_property_gallery_list_images($property_id);

        $data = hooks()->apply_filters('propertybase_landingpage_single_property_data', $data);

        propertybase_load_view($this->selectedThemeDetails['theme_property_path'], $data);

    }

    public function submit_lead($property_id)
    {
        if ($this->input->server('REQUEST_METHOD') !== 'POST') {
            show_error('Invalid request method', 405);
        }

        $this->load->model('leads_model');

        $name = $this->input->post('name');
        $email = $this->input->post('email');
        $phonenumber = $this->input->post('phonenumber');
        $description = $this->input->post('description');
        $defaultSourceForLeads = get_option('propertybase_default_selected_source_for_leads');
        $defaultStatusForLeads = get_option('propertybase_default_selected_status_for_leads');

        if (empty($name) || empty($defaultSourceForLeads) || empty($defaultStatusForLeads)) {
            $this->session->set_flashdata('error', 'Name, Status, and Source are required.');
            redirect($_SERVER['HTTP_REFERER']);
            return;
        }

        $this->load->model('propertybase_model');
        $propertyData = $this->propertybase_model->get($property_id);

        $leadData = [
            'name' => $name,
            'email' => $email,
            'phonenumber' => $phonenumber,
            'description' => $description,
            'dateadded' => date('Y-m-d H:i:s'),
            'source' => $defaultSourceForLeads,
            'status' => $defaultStatusForLeads,
            'assigned' => $propertyData->selected_agent,
        ];

        $leadData = hooks()->apply_filters('propertybase_before_insert_lead', $leadData);

        $lead_id = $this->leads_model->add($leadData);

        if ($lead_id) {
            hooks()->do_action('propertybase_after_insert_lead', $lead_id, $leadData);

            $this->propertybase_model->add_lead_to_property([
                'property_id' => $property_id,
                'lead_id' => $lead_id,
                'created_at' => date('Y-m-d H:i:s')
            ]);

            $this->session->set_flashdata('success', 'Submitted Successfully!');
            redirect($_SERVER['HTTP_REFERER']);
        } else {
            $this->session->set_flashdata('error', 'Failed to submit lead.');
            redirect($_SERVER['HTTP_REFERER']);
        }

        exit();
    }

}