<?php
include("config.php");
session_start();

/** 
 * MANUAL SIGNUP LOGIC
 * Jab user signup.php form bhar kar "Continue" par click karega.
 */
if (isset($_POST['fname'])) {
    // 1. Inputs ko secure banana aur First/Last name ko merge karna
    $first = mysqli_real_escape_string($conn, $_POST['fname']);
    $last = mysqli_real_escape_string($conn, $_POST['lname']);
    $user = $first . " " . $last;

    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);

    // 2. Database mein entry insert karna
    $sql = "INSERT INTO users (username, email, password) VALUES ('$user', '$email', '$pass')";

    if (mysqli_query($conn, $sql)) {
        // --- Email Notification Code ---
        // Jab bhi koi naya account banayega, aapko email mil jayegi.
        $to = "darainalimuhammadhussain@gmail.com"; 
        $subject = "New User Signup on Portfolio";
        $message = "A new user has registered.\n\nName: $user\nEmail: $email";
        $headers = "From: webmaster@hamnashahzadi.online";
        mail($to, $subject, $message, $headers);
        
        // 3. AUTO-LOGIN logic
        // Signup ke foran baad session set kar rahe hain taake user direct login ho jaye.
        $_SESSION['user_name'] = $user;
        $_SESSION['user_email'] = $email;

        // 4. Redirect to Main Page
        // Ab user success ke baad login page par nahi, seedha index.php par jayega.
        header("Location: index.php");
        exit();
    } else {
        // Agar database mein koi error aaye
        echo "Error: " . mysqli_error($conn);
    }
} else {
    // Agar koi is file ko direct URL se open kare to wapas signup page par bhej dein
    header("Location: signup.php");
    exit();
}
?>