<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Event\EventInterface;
use App\Controller\AppController;
use cake\ORM\TableRegistry;
use Cake\I18n\Time;
use Cake\Log\Log;

/**
 * Contactus Controller
 *
 * @method \App\Model\Entity\Contactus[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class ContactUsController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->slug = "contact-us";
        $this->loadModel('Contacts');      
    }

    public function beforeRender(EventInterface $event)
    {
        parent::beforeRender($event);
    }

    public function isAuthorized($user)
    {
        return true;
    }

    /**
     * Index method
     *
     * @return \Cake\Http\Response|null|void Renders view
     */
    public function index()
    {
        $this->edit(1);
        $this->render('edit');
    }


    /**
     * Add method
     *
     * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
     */

    public function add()
    {
        // Page title and new Contacts entity
        $pageTitle = 'Add Contacts';
        $cmscontacts = $this->Contacts->newEmptyEntity();

        // Check if the request is POST
        if ($this->request->is('post')) {
            $data = $this->request->getData();

            // Patch the request data to the Contacts entity
            $cmscontacts = $this->Contacts->patchEntity($cmscontacts, $this->request->getData());

            // Log the addition attempt
            Log::debug('Attempting to add contact', ['request_data' => $this->request->getData()]);

            // Attempt to save the new Contacts entity
            try {
                if ($this->Contacts->save($cmscontacts)) {
                    $this->Flash->success(__('Contact added successfully.'));
                    Log::info('Contact added successfully', ['contact_id' => $cmscontacts->id]);
                    return $this->redirect(['action' => 'pendingListings']);
                } else {
                    $this->Flash->error(__('The contact could not be saved. Please, try again.'));
                    Log::warning('Contact save failed', ['errors' => $cmscontacts->getErrors()]);
                }
            } catch (\Exception $e) {
                $this->Flash->error(__('An error occurred while saving the contact. Please, try again.'));
                Log::error('Exception occurred while saving contact', ['exception' => $e]);
            }
        }

        // Prepare view variables
        $this->set(compact('pageTitle', 'cmscontacts', 'cmscatlist', 'sectionlist'));
    }

    /**
     * Edit method
     *
     * @param string|null $id Contactus id.
     * @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function edit($id = 1)
    {
      
        // Attempt to find the contact with the given ID
        $ob = $this->Contacts->find('all')->where(['id' => $id])->first();

      

        if (!empty($ob)) {
            // Load the existing contact
            $cmscontacts = $this->Contacts->get($id);
        } else {
            // Create a new entity if not found
            $cmscontacts = $this->Contacts->newEmptyEntity();            
        }

        // Page title
        $pageTitle = 'General Contacts';

        // Check if the request is POST, PUT, or PATCH
        if ($this->request->is(['post', 'put', 'patch'])) {
            // Log the edit attempt
            Log::debug('Attempting to edit contact', ['request_data' => $this->request->getData(), 'contact_id' => $id]);

            $data = $this->request->getData();
          

            // Patch the request data to the Contacts entity
            $cmscontacts = $this->Contacts->patchEntity($cmscontacts, $data);
           
//             debug($cmscontacts);
// exit;
            // Attempt to save the updated Contacts entity
            try {
                if ($this->Contacts->save($cmscontacts)) {
                    $this->Flash->success(__('Contacts updated successfully.'));
                    Log::info('Contact updated successfully', ['contact_id' => $id]);
                    return $this->redirect(['action' => 'edit', $id]);
                } else {
                    $this->Flash->error(__('The contact could not be saved. Please, try again.'));
                    Log::warning('Contact save failed', ['errors' => $cmscontacts->getErrors()]);
                }
            } catch (\Exception $e) {
                $this->Flash->error(__('An error occurred while saving the contact. Please, try again.'));
                Log::error('Exception occurred while saving contact', ['exception' => $e]);
            }
        }

        // Prepare view variables
        $this->set(compact('pageTitle', 'cmscontacts'));
    }

    

  
}
