<?php
header("Content-Type: application/json; charset=UTF-8");
require_once "db.php";

$data = json_decode(file_get_contents("php://input"), true);
$PID = intval($data['PID'] ?? 0);

$sql = ($PID === 0)
    ? "SELECT id, project_name, project_owner, project_status, project_location, project_cost, project_duration, created_at, AttachmentPath FROM PrjectsMH ORDER BY created_at DESC"
    : "SELECT id, project_name, project_owner, project_status, project_location, project_cost, project_duration, created_at, AttachmentPath FROM PrjectsMH WHERE id = ? ORDER BY created_at DESC";

$stmt = $conn->prepare($sql);
if ($PID !== 0) {
    $stmt->bind_param("i", $PID);
}
$stmt->execute();
$result = $stmt->get_result();

$projects = [];
while ($row = $result->fetch_assoc()) {
    $projects[] = [
        "id" => $row["id"],
        "project_name" => $row["project_name"],
        "project_owner" => $row["project_owner"],
        "project_status" => $row["project_status"],
        "project_location" => $row["project_location"],
        "project_cost" => $row["project_cost"],
        "project_duration" => $row["project_duration"],
        "created_at" => $row["created_at"],
        "AttachmentPath" => $row["AttachmentPath"] ?? ""
    ];
}

echo json_encode(["status" => "success", "data" => $projects]);

$stmt->close();
$conn->close();
?>
