<?php
require_once dirname(__DIR__) . '/models/Project.php';
require_once dirname(__DIR__) . '/models/ProjectTask.php';
require_once dirname(__DIR__) . '/models/User.php';
require_once dirname(__DIR__) . '/../config/db.php';

class ProjectController {
    private $conn;

    public function __construct() {
        $this->conn = connectDB();
    }

    /**
     * Display a listing of all projects.
     */
    public function index() {
        $project = new Project($this->conn);
        $stmt = $project->readAll();
        $projects = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // We'll create this view file in the next steps
        require_once dirname(__DIR__) . '/../views/projects/index.php';
    }

    /**
     * Show the form for creating a new project.
     */
    public function create() {
        // We'll create this view file in the next steps
        require_once dirname(__DIR__) . '/../views/projects/create.php';
    }

    /**
     * Store a newly created project in the database.
     */
    public function store() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $project = new Project($this->conn);

            $project->project_name = $_POST['project_name'];
            $project->description = $_POST['description'];
            $project->start_date = $_POST['start_date'];
            $project->end_date = $_POST['end_date'];
            $project->status = $_POST['status'];
            $project->created_by_user_id = $_SESSION['user_id']; // Assuming user ID is in session

            if ($project->create()) {
                header("Location: ?page=projects&message=create_success");
                exit();
            } else {
                header("Location: ?page=project_create&error=create_failed");
                exit();
            }
        }
    }

    /**
     * Display the specified project and its tasks.
     */
    public function show() {
        $id_project = $_GET['id'] ?? null;
        if (!$id_project) {
            header("Location: ?page=projects&error=invalid_id");
            exit();
        }

        // Fetch project details
        $project = new Project($this->conn);
        $project->id_project = $id_project;
        $project_exists = $project->readOne();

        if (!$project_exists) {
            header("Location: ?page=projects&error=not_found");
            exit();
        }
        $project_data = $project;

        // Fetch tasks for the project
        $task = new ProjectTask($this->conn);
        $stmt = $task->readByProjectId($id_project);
        $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Fetch users for assignee dropdown
        $user = new User($this->conn);
        $users = $user->getAllUsers();

        // We'll create this view file in the next steps
        require_once dirname(__DIR__) . '/../views/projects/show.php';
    }

    /**
     * Store a new task for a project.
     */
    public function storeTask() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $task = new ProjectTask($this->conn);

            $id_project = $_POST['id_project'];
            $task->id_project = $id_project;
            $task->task_name = $_POST['task_name'];
            $task->description = $_POST['description'];
            $task->assignee_user_id = $_POST['assignee_user_id'];
            $task->start_date = $_POST['start_date'];
            $task->due_date = $_POST['due_date'];
            $task->status = $_POST['status'];

            if ($task->create()) {
                header("Location: ?page=project_show&id=" . $id_project . "&message=task_create_success");
                exit();
            } else {
                header("Location: ?page=project_show&id=" . $id_project . "&error=task_create_failed");
                exit();
            }
        }
    }
    
    /**
     * Update the status of a task (e.g., via AJAX).
     */
    public function updateTaskStatus() {
        header('Content-Type: application/json');
        
        $input = json_decode(file_get_contents('php://input'), true);
        $id_task = $input['id_task'] ?? null;
        $new_status = $input['status'] ?? null;

        if (!$id_task || !$new_status) {
            echo json_encode(['success' => false, 'message' => 'Invalid input.']);
            exit();
        }

        $task = new ProjectTask($this->conn);
        $task->id_task = $id_task;
        if ($task->readOne()) { // readOne populates the object
            $task->status = $new_status;
            
            // Only update the status field by creating a specific method or enhancing update()
            // For now, the existing update() updates all fields, which is not ideal for just a status change.
            // Let's create a dedicated method in the model.
            if ($task->updateStatus($new_status)) { // We will add this method to the model
                 echo json_encode(['success' => true]);
            } else {
                 echo json_encode(['success' => false, 'message' => 'Database update failed.']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Task not found.']);
        }
    }
    /**
     * Update the status of a project (e.g., via AJAX).
     */
    public function updateProjectStatus() {
        header('Content-Type: application/json');
        
        $input = json_decode(file_get_contents('php://input'), true);
        $id_project = $input['id_project'] ?? null;
        $new_status = $input['status'] ?? null;

        if (!$id_project || !$new_status) {
            echo json_encode(['success' => false, 'message' => 'Invalid input.']);
            exit();
        }

        $project = new Project($this->conn);
        if ($project->updateStatus($new_status, $id_project)) {
             echo json_encode(['success' => true]);
        } else {
             echo json_encode(['success' => false, 'message' => 'Database update failed.']);
        }
        exit();
    }

    /**
     * Delete a task (e.g., via AJAX).
     */
    public function deleteTask() {
        header('Content-Type: application/json');
        
        $input = json_decode(file_get_contents('php://input'), true);
        $id_task = $input['id_task'] ?? null;

        if (!$id_task) {
            echo json_encode(['success' => false, 'message' => 'Invalid input.']);
            exit();
        }

        $task = new ProjectTask($this->conn);
        $task->id_task = $id_task;
        
        if ($task->delete()) {
             echo json_encode(['success' => true]);
        } else {
             echo json_encode(['success' => false, 'message' => 'Database delete failed.']);
        }
        exit();
    }
}
