<?php include "check_login.php"; ?>
<?php
session_start();
include 'dbcon.php';

if (isset($_POST['assign_pm'])) {

    $project_id = (int)$_POST['project_id'];
    $pm_id      = (int)$_POST['pm_id'];

    if ($pm_id == 0) {
        $_SESSION['assign_error'] = "Please select a Project Manager.";
        header("Location: enquiry_view.php?project_id=$project_id");
        exit;
    }

    // already assigned check
    $chk = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT pm_id FROM projects WHERE id=$project_id"
    ));

    if (!empty($chk['pm_id'])) {
        $_SESSION['assign_error'] = "Project is already assigned.";
        header("Location: enquiry_view.php?project_id=$project_id");
        exit;
    }

    // assign PM
    $ok = mysqli_query($conn,"
        UPDATE projects 
        SET pm_id=$pm_id, status='In Progress'
        WHERE id=$project_id
    ");

    if ($ok) {

        // create phases
        $phases = [
            1 => "Biomass Availability",
            2 => "Technical Viability",
            3 => "Financial Viability",
            4 => "Risk Assessment & Closure"
        ];

        foreach ($phases as $no => $name) {
            mysqli_query($conn,"
                INSERT INTO project_phases (project_id,phase_no,phase_name,status)
                VALUES ($project_id,$no,'$name','pending')
            ");
        }

        // unlock phase 1
        mysqli_query($conn,"
            UPDATE project_phases 
            SET status='in_progress'
            WHERE project_id=$project_id AND phase_no=1
        ");

        // notify PM
        mysqli_query($conn,"
            INSERT INTO notifications (user_id,role,type,title,message,link)
            VALUES (
                $pm_id,'pm','assignment',
                'New Project Assigned',
                'Phase 1 (Biomass Availability) started',
                'enquiry_view.php?project_id=$project_id'
            )
        ");

        $_SESSION['assign_success'] = "Project Manager assigned successfully.";
    } else {
        $_SESSION['assign_error'] = "Something went wrong while assigning.";
    }

    header("Location: enquiry_view.php?project_id=$project_id");
    exit;
}
