<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'admin/database.php';
require_once "send_email.php";

class Submit extends database
{
    public function index($data)
    {
        
        return $this->insert('submission', $data);
    }
	
  public function getEmail()
    {
        return $this->fetchRow('email');
    }
}

if(!isset($_POST['data']) || $_POST['data']== "")
{
    http_response_code(400);
    echo json_encode('Data Not Found');
    exit;
}
$data = $_POST['data'];

$errorMessage = '';


if(trim($data['name']) == '')
{
    $errorMessage.= "Name is required<br/>";
}

if(trim($data['surname']) == '')
{
    $errorMessage.= "Surname is required<br/>";
}
if(trim($data['preferred_date']) == '')
{
    $errorMessage.= "Preferred Date is required<br/>";
}
else
{
      $data['preferred_date'];
     $data['preferred_date'] = date("Y-m-d", strtotime($data['preferred_date']));
}

if(trim($data['email']) == '')
{
    $errorMessage.= "Email is required<br/>";
}
else if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL))
{
    $errorMessage.= "Please enter a valid email<br/>";
}

if(trim($data['no_of_persons']) == '')
{
    $errorMessage.= "No. of Persons is required<br/>";
}

if(trim($data['message']) == '')
{
    $errorMessage.= "Message is required<br/>";
}

if(trim($data['terms']) != 1)
{
    $errorMessage.= "Please check Terms. <br/>";
}

if(trim($errorMessage) == '')
{
    $ins = new Submit();

    $res = $ins->index($data);
    if($res)
    {
        $email = $ins->getEmail();
         send_email($email['email'], $email['email'], 'New Contact Request', 'Name:' . $data['name'] . '<br/>Surname:' . $data['surname'] . '<br/>Preferred Date:' . date("d M Y", strtotime($data['preferred_date'])) . '<br/>Email:' . $data['email'] . '<br/>No. of Persons:' . $data['no_of_persons'] . '<br/>Message:' . $data['message'] . '<br/>Terms:' . $data['terms']);
        http_response_code(200);
        echo json_encode('Form Submitted Successfully');
        exit;
    }
                    
    http_response_code(500);
    echo json_encode(['error_description' => 'Something went wrong']);
    exit;
}

http_response_code(400);
echo json_encode(['error_description' => [$errorMessage]]);
exit;
?>