<?php
require '../require/conn.php';

// Enable MySQLi error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Set session cookie parameters BEFORE starting the session
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);

// Start the session
session_start();

// Prevent session fixation attacks
session_regenerate_id(true);

// Function to sanitize input
function sanitizeInput($data) {
    return htmlspecialchars(stripslashes(trim($data)), ENT_QUOTES, 'UTF-8');
}

// Handle registration request
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo json_encode(["status" => "error", "message" => "Invalid CSRF token."]);
        exit();
    }

    // Sanitize inputs
    $firstName = sanitizeInput($_POST['firstName']);
    $lastName = sanitizeInput($_POST['lastName']);
    $phone = sanitizeInput($_POST['phone']);
    $email = sanitizeInput($_POST['email']);
    $password = sanitizeInput($_POST['password']);
    $confirmPassword = sanitizeInput($_POST['confirm_password']);
    $transactionPin = sanitizeInput($_POST['transaction_pin']);

    // Validate input fields
    if (empty($firstName) || empty($lastName) || empty($phone) || empty($email) || empty($password) || empty($confirmPassword) || empty($transactionPin)) {
        echo json_encode(["status" => "error", "message" => "All fields are required."]);
        exit();
    }

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(["status" => "error", "message" => "Invalid email format."]);
        exit();
    }

    // Validate phone number format (updated regex)
    if (!preg_match('/^\+?\d{8,15}$/', $phone)) {
        echo json_encode(["status" => "error", "message" => "Invalid phone number format."]);
        exit();
    }

    // Validate transaction PIN (must be 4 digits)
    if (!preg_match('/^\d{4}$/', $transactionPin)) {
        echo json_encode(["status" => "error", "message" => "Transaction PIN must be 4 digits."]);
        exit();
    }

    // Check if password and confirm password match
    if ($password !== $confirmPassword) {
        echo json_encode(["status" => "error", "message" => "Passwords do not match."]);
        exit();
    }

    // Generate a 10-character hash for the password
    $hashedPassword = substr(hash('sha256', $password), 0, 10);

    // Hash the transaction PIN securely
    $hashedTransactionPin = password_hash($transactionPin, PASSWORD_DEFAULT);

    // Check if email or phone already exists
    $checkQuery = "SELECT id FROM jamaa WHERE email = ? OR phone = ?";
    $checkStmt = $conn->prepare($checkQuery);
    $checkStmt->bind_param("ss", $email, $phone);
    $checkStmt->execute();
    $checkStmt->store_result();

    if ($checkStmt->num_rows > 0) {
        echo json_encode(["status" => "error", "message" => "Email or phone number already exists."]);
        exit();
    }
    $checkStmt->close();

    // Insert user data into the database
    $query = "INSERT INTO jamaa (firstName, lastName, email, phone, password, transaction_pin) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($query);

    try {
        $stmt->bind_param("ssssss", $firstName, $lastName, $email, $phone, $hashedPassword, $hashedTransactionPin);
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Registration successful!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Registration failed. Please try again."]);
        }
    } catch (mysqli_sql_exception $e) {
        echo json_encode(["status" => "error", "message" => "Error: " . $e->getMessage()]);
    }

    $stmt->close();
    $conn->close();
    exit();
}

// Generate CSRF token for the form
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
?>













<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Create Account</title>
  <!-- SweetAlert2 CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: Arial, sans-serif;
      background-color: #f8f8f8;
    }

    .container {
      width: 100%;
      min-height: 100vh;
      background-color: #fff;
    }

    .header {
      width: 100%;
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: green;
      border-bottom-left-radius: 40px;
      border-bottom-right-radius: 40px;
    }

    .header img {
      width: 1500px; 
      height: 50px;
      object-fit: contain;
      padding: 10px;
    }

    .form-wrapper {
      padding: 20px;
      margin-top: -30px;
    }

    h2 {
      text-align: center;
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 5px;
    }

    .subtext {
      text-align: center;
      font-size: 12px;
      color: #333;
      margin-bottom: 20px;
      line-height: 1.4;
    }

    form {
      width: 100%;
    }

    .form-group {
      display: flex;
      justify-content: space-between;
      gap: 10px;
      margin-bottom: 15px;
      width: 100%;
    }

    .form-group.single {
      display: flex;
      justify-content: center;
    }

    .form-group.single input {
      width: 100%;
    }

    .input-container {
      position: relative;
      width: 48%; /* Adjust width to fit two inputs in one row */
    }

    input {
      width: 100%;
      height: 45px;
      padding: 0 40px 0 10px; /* Add padding-right for the eye icon */
      border: 1px solid #333;
      border-radius: 10px;
      font-size: 14px;
      font-weight: bold;
      outline: none;
    }

    input::placeholder {
      color: #000;
      font-weight: bold;
    }

    .toggle-password {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      cursor: pointer;
    }

    .toggle-password img {
      width: 20px;
      height: 20px;
    }

    button {
      width: 100%;
      height: 50px;
      background-color: #d9d9d9;
      color: #000;
      font-size: 18px;
      font-weight: normal;
      border: 1px solid #333;
      border-radius: 10px;
      cursor: pointer;
      margin-top: 10px;
    }

    .login-link {
      text-align: center;
      margin-top: 15px;
      font-size: 12px;
    }

    .login-link a {
      color: #000;
      text-decoration: none;
      font-weight: bold;
    }

    @media (max-width: 480px) {
      .input-container {
        width: 48%; /* Maintain two inputs in one row */
      }

      input {
        padding-right: 40px; /* Ensure padding for the eye icon */
      }

      .toggle-password {
        right: 15px; /* Adjust position for better alignment */
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <!-- Replace with your actual image source -->
      <img src="logo.png" alt="Image" />
    </div>
    <br>
    <form class="form-wrapper" id="registrationForm" method="POST" action="">
      <!-- CSRF Token -->
      <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

      <!-- First Name & Last Name -->
      <div class="form-group">
        <div class="input-container">
          <input type="text" name="firstName" placeholder="First Name" required />
        </div>
        <div class="input-container">
          <input type="text" name="lastName" placeholder="Last Name" required />
        </div>
      </div>

      <!-- Phone No & Transaction Pin -->
      <div class="form-group">
        <div class="input-container">
          <input type="number" name="phone" placeholder="Phone No" required />
        </div>
        <div class="input-container">
          <input type="number" name="transaction_pin" placeholder="Transaction Pin" required />
        </div>
      </div>

      <!-- Email Full Width -->
      <div class="form-group single">
        <input type="email" name="email" placeholder="Email" required />
      </div>

      <!-- Password & Confirm Password -->
      <div class="form-group">
        <div class="input-container">
          <input type="password" name="password" id="password" placeholder="Password" required />
          <span class="toggle-password" onclick="togglePasswordVisibility('password')">
            <img src="eye.png" alt="Toggle Password Visibility" />
          </span>
        </div>
        <div class="input-container">
          <input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" required />
          <span class="toggle-password" onclick="togglePasswordVisibility('confirm_password')">
            <img src="eye.png" alt="Toggle Password Visibility" />
          </span>
        </div>
      </div>

      <!-- Create Account Button -->
      <button type="submit">Create Account</button>
    </form>

    <!-- Login Link -->
    <div class="login-link">
      <a href="#">Login Account</a>
    </div>
  </div>

  <!-- SweetAlert2 JS -->
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script>
    // Function to toggle password visibility
    function togglePasswordVisibility(fieldId) {
      const field = document.getElementById(fieldId);
      if (field.type === "password") {
        field.type = "text";
      } else {
        field.type = "password";
      }
    }

    // Handle form submission
    document.getElementById('registrationForm').addEventListener('submit', function(event) {
      event.preventDefault(); // Prevent default form submission

      // Get form data
      const formData = new FormData(this);

      // Send form data to the server using Fetch API
      fetch('<?php echo $_SERVER["PHP_SELF"]; ?>', {
        method: 'POST',
        body: formData
      })
      .then(response => response.json())
      .then(data => {
        if (data.status === "success") {
          // Show success message
          Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: data.message,
          }).then(() => {
            // Redirect to another page or reset the form
            window.location.href = 'login.html'; // Replace with your desired redirect URL
          });
        } else {
          // Show error message
          Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: data.message,
          });
        }
      })
      .catch(error => {
        console.error('Error:', error);
        Swal.fire({
          icon: 'error',
          title: 'Oops...',
          text: 'An error occurred. Please try again.',
        });
      });
    });
  </script>
</body>
</html>