<?php
session_start();
include 'connect.php';

if (isset($_POST['signup'])) {
    // Collecting form data
    $firstName = trim($_POST['fname']);
    $lastname = trim($_POST['lname']);
    $email = trim($_POST['email']);
    $user_type = trim($_POST['user_type']); // Make sure this matches the form field name
    $username = trim($_POST['username']);
    $contact = trim($_POST['contact']);
    $password = trim($_POST['password']);
    $password = md5($password); // Note: Consider using password_hash() instead of md5 for better security

    // Check if email already exists
    $checkEmail = "SELECT * FROM users WHERE email = ?";
    $stmt = $conn->prepare($checkEmail);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        echo "<script>alert('Email address already exists.');window.location.href = 'createAccount.php';</script> ";
        exit();
    } else {
        // Insert user into the database using prepared statement
        $insertQuery = "INSERT INTO users (firstname, lastname, username, email, password, phone, user_type) 
                       VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($insertQuery);
        $stmt->bind_param("sssssss", $firstName, $lastname, $username, $email, $password, $contact, $user_type);

        if ($stmt->execute()) {
            // Get the user_id of the newly inserted user
            $user_id = $stmt->insert_id;

            // Insert a new row into job_seekers table with the same user_id
            if ($user_type === 'Job seeker') { // Only insert if the user is a jobseeker
                $insertJobSeekerQuery = "INSERT INTO job_seekers (user_id) VALUES (?)";
                $stmtJobSeeker = $conn->prepare($insertJobSeekerQuery);
                $stmtJobSeeker->bind_param("i", $user_id);
                if ($stmtJobSeeker->execute()) {
                    echo "<script>alert('Jobseeker profile created successfully!');</script>";
                } else {
                    echo "Error inserting into job_seekers table: " . $stmtJobSeeker->error;
                }
                $stmtJobSeeker->close();
            } elseif ($user_type === 'Employer') { // Only insert if the user is an Employer
                $insertEmployerQuery = "INSERT INTO employers (user_id) VALUES (?)";
                $stmtEmployer = $conn->prepare($insertEmployerQuery);
                $stmtEmployer->bind_param("i", $user_id);
                if ($stmtEmployer->execute()) {
                    echo "<script>alert('Employer profile created successfully!');</script>";
                } else {
                    echo "Error inserting into employers table: " . $stmtEmployer->error;
                }
                $stmtEmployer->close();
            }
            $stmt->close();
            header("Location: index.php");
            exit();
        } else {
            echo "Error: " . $stmt->error;
        }
        $stmt->close();
    }
}


// Login section
if (isset($_POST['Login'])) {
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $password = md5($password);

    // Use prepared statement for login
    $sql = "SELECT * FROM users WHERE email = ? AND password = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $email, $password);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $_SESSION['email'] = $row['email'];
        $_SESSION['user_type'] = $row['user_type']; // Store user type in session
        $_SESSION['user_id'] = $row['user_id']; // Store user ID in session
        $_SESSION['username'] = $row['username']; // Store username in session

        if (strtolower($row['user_type']) === 'employer') {

            $employerQuery = "SELECT employer_id FROM employers WHERE user_id = ?";
            $employerStmt = $conn->prepare($employerQuery);
            $employerStmt->bind_param("i", $row['user_id']);
            $employerStmt->execute();
            $employerResult = $employerStmt->get_result();
            if ($employerResult->num_rows > 0) {
                $employerRow = $employerResult->fetch_assoc();
                $_SESSION['employer_id'] = $employerRow['employer_id']; // Store employer_id in session
            }
        }
        
        else if (strtolower($row['user_type']) === 'job seeker') {

            $job_seekereQuery = "SELECT seeker_id FROM job_seekers WHERE user_id = ?";
            $job_seekerStmt = $conn->prepare($job_seekereQuery);
            $job_seekerStmt->bind_param("i", $row['user_id']);
            $job_seekerStmt->execute();
            $job_seekerResult = $job_seekerStmt->get_result();
            if ($job_seekerResult->num_rows > 0) {
                $job_seekerRow = $job_seekerResult->fetch_assoc();
                $_SESSION['seeker_id'] = $job_seekerRow['seeker_id']; // Store seeker_id in session
            }
            
    }
        header("Location: index");
        exit();
    } else {
        echo "<script>alert('Incorrect email or password.'); window.location.href = 'login';</script>";
        exit();
    }
}
?>