<?php
include "check_login.php";
include "dbcon.php";

$phase_id   = (int)$_POST['phase_id'];
$project_id = (int)$_POST['project_id'];
$message    = trim($_POST['message']);

$pm_id = $userpmid; // logged-in PM id

if ($message == '') {
    exit;
}

/* 🔐 SECURITY CHECK: project isi PM ka hai ya nahi */
$chk = mysqli_query($conn, "
    SELECT id FROM projects 
    WHERE id = $project_id 
      AND pm_id = $pm_id
");

if (mysqli_num_rows($chk) == 0) {
    http_response_code(403);
    exit('Unauthorized');
}

/* 🔐 SECURITY CHECK: phase isi project ka hai */
$chk2 = mysqli_query($conn, "
    SELECT id FROM project_phases 
    WHERE id = $phase_id 
      AND project_id = $project_id
");

if (mysqli_num_rows($chk2) == 0) {
    http_response_code(403);
    exit('Invalid phase');
}

/* ✅ INSERT MESSAGE */
mysqli_query($conn,"
    INSERT INTO phase_messages
    (project_id, phase_id, sender_role, sender_id, message)
    VALUES
    ($project_id, $phase_id, 'pm', $pm_id, '$message')
");


/* 🔔 ADMIN NOTIFICATION */
$title   = "New Phase Message";
$msg     = "PM sent a message in Phase discussion";
$link    = "phase_review.php?phase_id=$phase_id&project_id=$project_id";

mysqli_query($conn, "
    INSERT INTO notifications (role, type, title, message, link)
    VALUES ('admin', 'discussion', '$title', '$msg', '$link')
");
