<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
 include '../config/index.php';
 include '../module/index.php';

 
$data = new Database;

$con = $data->connect();

$user = new User($con);

$post = filter_var_array($_POST,FILTER_SANITIZE_FULL_SPECIAL_CHARS);


$user->first_name  = $post['name'];
$user->address    =  $post['address'];
$user->phone      =  $post['phone'];
$user->country    =  $post['country'];

$user->sex        = $post['gender'];
$user->email      = $post['email'];
$user->password   = $post['password'];

$temp     = $_FILES['file']['tmp_name'];


if(!$user->first_name || !$user->address || !$user->phone || !$user->country){
    $error = "fill all required fields";
    echo $data->redirect('../../register.php?errors=' . urlencode($error));
    exit();
}
    
$originalImageName = $_FILES['file']['name']; // Keep original name first
$ext = strtolower(pathinfo($originalImageName, PATHINFO_EXTENSION)); // Get extension



$valid_extensions = array('jpeg', 'jpg', 'png'); // valid extensions

if (!in_array($ext, $valid_extensions)) {
    $error = "Invalid image format. Only jpeg, jpg, png are allowed";
    echo $data->redirect('../../register.php?error=' . urlencode($error));
    exit;
}

$user->image = time() . '.' . $ext; // Now assign the new image name
$path = '../assets/img/' . $user->image; // Upload path

if($user->emailExist($user->email)){
   $error ="email address has already been used";
   echo $data->redirect('../../register.php?errors='.$error);
}else{
   move_uploaded_file($temp,$path);
   if($user->CreateAccount()){
      $error ="Account Creation successfull <br> A email notification has been sent to your email address";
      echo $data->redirect('../../login.php?error='.$error);
   }
}

?>