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

/* BASIC VALIDATION */
if (!isset($_POST['action']) || $_POST['action'] !== 'approve') {
    echo 'invalid';
    exit;
}

$phase_id   = isset($_POST['phase_id']) ? (int)$_POST['phase_id'] : 0;
$project_id = isset($_POST['project_id']) ? (int)$_POST['project_id'] : 0;

if ($phase_id == 0 || $project_id == 0) {
    echo 'missing';
    exit;
}

/* ===============================
   1️⃣ APPROVE CURRENT PHASE
================================ */
mysqli_query($conn,"
    UPDATE project_phases
    SET status='approved'
    WHERE id=$phase_id AND project_id=$project_id
");

/* ===============================
   2️⃣ GET CURRENT PHASE NO
================================ */
$curQ = mysqli_query($conn,"
    SELECT phase_no FROM project_phases
    WHERE id=$phase_id
");
$cur = mysqli_fetch_assoc($curQ);
$current_phase_no = (int)$cur['phase_no'];

/* ===============================
   3️⃣ CHECK NEXT PHASE
================================ */
$nextQ = mysqli_query($conn,"
    SELECT id FROM project_phases
    WHERE project_id=$project_id
      AND phase_no = ".($current_phase_no + 1)."
");

if (mysqli_num_rows($nextQ) > 0) {

    /* ===============================
       NEXT PHASE EXISTS → START IT
    ================================ */
    mysqli_query($conn,"
        UPDATE project_phases
        SET status='in_progress'
        WHERE project_id=$project_id
          AND phase_no = ".($current_phase_no + 1)."
    ");

} else {

    /* ===============================
       LAST PHASE → PROJECT COMPLETE
    ================================ */
    mysqli_query($conn,"
        UPDATE projects
        SET status='complete'
        WHERE id=$project_id
    ");
}

/* ===============================
   4️⃣ OPTIONAL: TIMELINE ENTRY
================================ */
mysqli_query($conn,"
    INSERT INTO phase_timeline
    (project_id, phase_id, action)
    VALUES
    ($project_id, $phase_id, 'approved')
");

/* ===============================
   5️⃣ RESPONSE FOR AJAX
================================ */
echo 'success';
exit;
