<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include database configuration
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../vendor/autoload.php';

// Load environment variables (comment this out if not using dotenv)
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();

session_start(); // Start session to manage login state

// Get current request URI
$requestUri = $_SERVER['REQUEST_URI'];

// Handle root ("/") route
if ($requestUri === '/' || $requestUri === '/index') {
    // Redirect to login if user is not logged in
    if (!isset($_SESSION['user_id'])) {
        header('Location: /login');
        exit;
    } else {
        header('Location: /workers'); // Redirect to worker dashboard if logged in
        exit;
    }
}

// Route to worker dashboard if logged in
if ($requestUri === '/workers') {
    if (!isset($_SESSION['user_id'])) {
        header('Location: /login');
        exit;
    }
    include __DIR__ . '/worker.html'; // Make sure this path is correct
} 
// Route to login page
else if ($requestUri === '/login') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $email = $_POST['email'];
        $password = $_POST['password'];

        // Fetch user from database
        $query = "SELECT * FROM users WHERE email = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();

        // Verify user exists and password is correct
        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id']; // Set session
            header('Location: /workers'); // Redirect to worker dashboard
            exit;
        } else {
            $error = "Invalid email or password";
        }
    }
    include __DIR__ . '/../public/login.php'; // Load the login form
} 
// Route to register page
else if ($requestUri === '/register') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $username = $_POST['username'];
        $email = $_POST['email'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // Hash password

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

        if ($result->num_rows > 0) {
            $error = "Email already registered!";
        } else {
            // Insert new user
            $query = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
            $stmt = $conn->prepare($query);
            $stmt->bind_param('sss', $username, $email, $password);
            if ($stmt->execute()) {
                header('Location: /login'); // Redirect to login after registration
                exit;
            } else {
                $error = "Registration failed!";
            }
        }
    }
    include __DIR__ . '/../public/register.php'; // Load the register form
}
// Forgot password route
else if ($requestUri === '/forgot-password') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $email = $_POST['email'];

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

        if ($user) {
            // Generate a unique token for password reset
            $token = bin2hex(random_bytes(50)); // 50 characters long token

            // Store token in the database with an expiry (1 hour)
            $query = "UPDATE users SET reset_token = ?, reset_token_expiry = DATE_ADD(NOW(), INTERVAL 1 HOUR) WHERE email = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param('ss', $token, $email);
            $stmt->execute();

            // Send password reset email
            $resetLink = "http://localhost/worker-management-app/reset-password?token=$token";
            $subject = "Password Reset for TaskPro";
            $message = "Click the following link to reset your password: $resetLink";
            $headers = "From: no-reply@taskpro.com";

            if (mail($email, $subject, $message, $headers)) {
                echo "A password reset link has been sent to your email.";
            } else {
                echo "Failed to send password reset email.";
            }
        } else {
            echo "No account found with that email.";
        }
    } else {
        include __DIR__ . '/../public/forgot_password.php'; // Load the forgot password form
    }
}
// Reset password route
else if ($requestUri === '/reset-password') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $newPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $token = $_POST['token'];

        // Find the user by token and make sure it's still valid
        $query = "SELECT * FROM users WHERE reset_token = ? AND reset_token_expiry > NOW()";
        $stmt = $conn->prepare($query);
        $stmt->bind_param('s', $token);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();

        if ($user) {
            // Update password and remove the token
            $query = "UPDATE users SET password = ?, reset_token = NULL, reset_token_expiry = NULL WHERE id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param('si', $newPassword, $user['id']);
            if ($stmt->execute()) {
                echo "Password reset successfully!";
                header('Location: /login'); // Redirect to login page
                exit;
            } else {
                echo "Failed to reset password!";
            }
        } else {
            echo "Invalid or expired token.";
        }
    } else {
        include __DIR__ . '/../public/reset_password.php'; // Load the reset password form
    }
}
// Logout route
else if ($requestUri === '/logout') {
    session_destroy(); // Destroy session and logout
    header('Location: /login');
    exit;
}
// Default to 404 for unknown routes
else {
    echo "404 - Page not found. Route: " . $requestUri;
}
