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

/* ===============================
   BASIC VALIDATION
================================ */
if (
    !isset($_POST['phase_id']) ||
    !isset($_POST['project_id']) ||
    !isset($_FILES['report'])
) {
    die("Invalid Request");
}

$phase_id   = (int)$_POST['phase_id'];
$project_id = (int)$_POST['project_id'];
$remarks    = mysqli_real_escape_string($conn, $_POST['remarks']);
$pm_id      = $userpmid; // logged-in PM ID

/* ===============================
   SECURITY CHECKS
================================ */

/* 1️⃣ Project belongs to PM */
$chk = mysqli_query($conn,"
    SELECT id FROM projects 
    WHERE id = $project_id 
      AND pm_id = $pm_id
");
if (mysqli_num_rows($chk) == 0) {
    die("Unauthorized access");
}

/* 2️⃣ Phase belongs to project & editable */
$phaseQ = mysqli_query($conn,"
    SELECT status FROM project_phases 
    WHERE id = $phase_id 
      AND project_id = $project_id
");
if (mysqli_num_rows($phaseQ) == 0) {
    die("Invalid Phase");
}

$phase = mysqli_fetch_assoc($phaseQ);
if (!in_array($phase['status'], ['in_progress','correction'])) {
    die("Phase not editable");
}

/* ===============================
   FILE UPLOAD
================================ */

$uploadDir = "../uploads/phase_reports/";
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$ext = pathinfo($_FILES['report']['name'], PATHINFO_EXTENSION);
$allowed = ['pdf','doc','docx','xls','xlsx','png','jpg'];

if (!in_array(strtolower($ext), $allowed)) {
    die("Invalid file type");
}

$filename = time().'_PM'.$pm_id.'_PH'.$phase_id.'.'.$ext;
$filepath = $uploadDir.$filename;

if (!move_uploaded_file($_FILES['report']['tmp_name'], $filepath)) {
    die("File upload failed");
}

/* ===============================
   SAVE REPORT
================================ */

mysqli_query($conn,"
    INSERT INTO phase_reports
    (project_id, phase_id, pm_id, report_file, remarks)
    VALUES
    ($project_id, $phase_id, $pm_id, '$filename', '$remarks')
");

/* ===============================
   UPDATE PHASE STATUS
================================ */

mysqli_query($conn,"
    UPDATE project_phases 
    SET status = 'submitted'
    WHERE id = $phase_id
");

/* ===============================
   ADMIN NOTIFICATION
================================ */

$title = "Phase Report Submitted";
$msg   = "PM submitted report for Phase ID #$phase_id";
$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', 'phase_report', '$title', '$msg', '$link')
");

/* ===============================
   REDIRECT BACK
================================ */

header("Location: phase_work.php?phase_id=$phase_id&project_id=$project_id&success=1#historyTab");

exit;
