#!/bin/bash

# Define the base directory where the system will be set up
BASE_DIR="/public_html/tasks"

# Step 1: Create the required directories
mkdir -p $BASE_DIR/{auth,tasks,admin,user,config}

# Step 2: Create the database setup script
cat <<EOL > $BASE_DIR/config/db_setup.sql
-- Create the necessary tables for the task management system
CREATE TABLE IF NOT EXISTS users (
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    email VARCHAR(255),
    role ENUM('User', 'Admin') DEFAULT 'User'
);

CREATE TABLE IF NOT EXISTS tasks (
    task_id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    status ENUM('Assigned', 'In Progress', 'Completed', 'Failed') DEFAULT 'Assigned',
    due_date DATE,
    assigned_user_id INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS employee_involvement (
    task_id INT,
    user_id INT,
    involvement_type ENUM('Creator', 'Executor') DEFAULT 'Executor',
    PRIMARY KEY (task_id, user_id),
    FOREIGN KEY (task_id) REFERENCES tasks(task_id),
    FOREIGN KEY (user_id) REFERENCES users(user_id)
);

-- Insert a test admin user
INSERT INTO users (username, password_hash, role) VALUES ('admin', PASSWORD('AdminPass'), 'Admin');
EOL

# Step 3: Create PHP configuration file for database connection
cat <<EOL > $BASE_DIR/config/db_connect.php
<?php
\$host = 'localhost';
\$db = 'task_management';
\$user = 'your_database_user';
\$pass = 'your_database_password';

try {
    \$pdo = new PDO("mysql:host=\$host;dbname=\$db", \$user, \$pass);
    \$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException \$e) {
    echo "Connection failed: " . \$e->getMessage();
}
?>
EOL

# Step 4: Create authentication-related files

# login.php
cat <<EOL > $BASE_DIR/auth/login.php
<?php
session_start();
include '../config/db_connect.php';
\$error = '';

if (\$_SERVER['REQUEST_METHOD'] == 'POST') {
    \$username = \$_POST['username'];
    \$password = \$_POST['password'];

    // Fetch the user from the database
    \$stmt = \$pdo->prepare("SELECT * FROM users WHERE username = :username");
    \$stmt->execute(['username' => \$username]);
    \$user = \$stmt->fetch(PDO::FETCH_ASSOC);

    if (\$user && password_verify(\$password, \$user['password_hash'])) {
        \$_SESSION['user_id'] = \$user['user_id'];
        header('Location: ../tasks/dashboard.php');
        exit();
    } else {
        \$error = 'Invalid username or password!';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-5">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <div class="card">
                <div class="card-header text-center">
                    <h3>Login</h3>
                </div>
                <div class="card-body">
                    <form method="POST" action="login.php">
                        <?php if (\$error): ?>
                            <div class="alert alert-danger"><?= \$error ?></div>
                        <?php endif; ?>
                        <div class="mb-3">
                            <label for="username" class="form-label">Username</label>
                            <input type="text" name="username" class="form-control" id="username" required>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="password" name="password" class="form-control" id="password" required>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">Login</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
EOL

# logout.php
cat <<EOL > $BASE_DIR/auth/logout.php
<?php
session_start();
session_unset();
session_destroy();
header('Location: login.php');
exit();
?>
EOL

# Step 5: Create task-related files

# dashboard.php
cat <<EOL > $BASE_DIR/tasks/dashboard.php
<?php
session_start();
if (!isset(\$_SESSION['user_id'])) {
    header('Location: ../auth/login.php');
    exit();
}

include '../config/db_connect.php';

// Fetch task data
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<!-- Sidebar, charts, and task data goes here -->
</body>
</html>
EOL

# Step 6: Create additional PHP files for tasks (create_task.php, edit_task.php, etc.)
# Add each file similarly to the examples above

# Step 7: Set appropriate permissions
chown -R www-data:www-data $BASE_DIR
chmod -R 755 $BASE_DIR

echo "Task Management System setup complete!"
