<?php

namespace Main\Controllers\Account;

use Main\Core\Controller;
use Main\Services\SeoService;
use PDO;

class ContactController extends Controller
{
		protected string $route_type = 'edit-contact';
		
    public function edit()
    {
	      SeoService::set('account.contact.edit');
			
        $contactInfo = db()->prepare("SELECT * FROM AccountContactInfo WHERE accountID = ?");
		    $contactInfo->execute(array(auth()->user()->id()));
		    $contactInfo = $contactInfo->fetch();
		    if (!$contactInfo) {
			    $contactInfo = [
				    "firstName" => "",
				    "lastName" => "",
				    "phoneNumber" => ""
			    ];
		    }
	    
		    if (isset($_GET["back"])) {
			    session()->set('back', get('back'));
		    }

        return $this->view('account.contact', compact('contactInfo'));
    }

    public function update()
    {
        validate([
            'firstName' => 'required',
            'lastName' => 'required',
            'phoneNumber' => 'required'
        ]);

        $checkAccountContactInfo = db()->prepare("SELECT * FROM AccountContactInfo WHERE accountID = ?");
        $checkAccountContactInfo->execute(array(auth()->user()->id()));
        $checkAccountContactInfo = $checkAccountContactInfo->fetch();
				
				$firstName = sanitize(input("firstName"));
				$lastName = sanitize(input("lastName"));
				$phoneNumber = sanitize(input("phoneNumber"));

        if ($checkAccountContactInfo) {
            $updateAccountContactInfo = db()->prepare("UPDATE AccountContactInfo SET firstName = ?, lastName = ?, phoneNumber = ? WHERE accountID = ?");
            $updateAccountContactInfo->execute(array($firstName, $lastName, $phoneNumber, auth()->user()->id()));
        }
        else {
            $insertAccountContactInfo = db()->prepare("INSERT INTO AccountContactInfo (accountID, firstName, lastName, phoneNumber) VALUES (?, ?, ?, ?)");
            $insertAccountContactInfo->execute(array(auth()->user()->id(), $firstName, $lastName, $phoneNumber));
        }
				
				if (session()->has('back')) {
					session()->remove('back');
					redirect(session()->get('back'));
				}

        return back()->flash("success", t__('Your profile has been updated.'));
    }
}