<?php
// Database connection parameters
$dsn = 'mysql:host=localhost;dbname=staff_portal';
$username = 'root';
$password = '';

try {
    // Create a PDO instance
    $pdo = new PDO($dsn, $username, $password);
    
    // Set PDO to throw exceptions on error
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    // Handle database connection error
    echo "Connection failed: " . $e->getMessage();
    exit();
}


// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
    // Redirect the user to the login page
    header("Location: login.php");
    exit();
}

// Initialize user_id
$user_id = $_SESSION['user_id'];

// Define the table names for each form
$tableNames = [
    1 => "users",
    2 => "education",
    3 => "work_history",
    4 => "work_history_two",
    5 => "church",
    6 => "accomadation",
    7 => "family",
    8 => "other_details",
    // Add more table names for additional forms
];

// Check which forms have been submitted by querying the database
$submittedForms = [];
foreach ($tableNames as $form => $tableName) {
    $query = "SELECT COUNT(*) FROM $tableName WHERE user_id = :user_id";
    $stmt = $pdo->prepare($query);
    $stmt->execute(['user_id' => $user_id]);
    $count = $stmt->fetchColumn();

    // Store the submission status for each form
    $submittedForms[$form] = ($count > 0);
    // Find the next form that hasn't been submitted
$nextForm = null;
foreach ($submittedForms as $form => $submitted) {
    if (!$submitted) {
        $nextForm = $form;
        break;
    }
}

if ($nextForm !== null) {
    // Redirect the user to the next form
    header("Location: form{$nextForm}.php");
    exit();
} else {
    // Redirect the user to a completion page or another location
    header("Location: completion.php");
    exit();
}

}
?>
