<?php
include '../connection.php';

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$action = $_GET['action'];

if ($action == 'fetch') {
    $sql = "SELECT ID, construction_title, under_supervision, assigned_budget, start_date, end_date FROM constructions";
    $result = $conn->query($sql);

    $constructions = array();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $constructions[] = $row;
        }
    }

    echo json_encode($constructions);
}

if ($action == 'fetch_details') {
    $construction_id = $_GET['construction_id'];
    $sql = "SELECT ID, details_date, construction_details FROM construction_details WHERE construction_id = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
    }
    $stmt->bind_param("i", $construction_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $details = array();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $details[] = $row;
        }
    }

    echo json_encode($details);
}

if ($action == 'add_construction') {
    $construction_title = $_POST['construction_title'];
    $under_supervision = $_POST['under_supervision'];
    $assigned_budget = $_POST['assigned_budget'];
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];

    $sql = "INSERT INTO constructions (construction_title, under_supervision, assigned_budget, start_date, end_date) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
    }
    $stmt->bind_param("ssdss", $construction_title, $under_supervision, $assigned_budget, $start_date, $end_date);

    if ($stmt->execute()) {
        echo "Construction added successfully";
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}

if ($action == 'add_details') {
    $construction_id = $_POST['construction_id'];
    $details_date = $_POST['details_date'];
    $construction_details = $_POST['construction_details'];

    $sql = "INSERT INTO construction_details (construction_id, details_date, construction_details) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE details_date = ?, construction_details = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
    }
    $stmt->bind_param("issss", $construction_id, $details_date, $construction_details, $details_date, $construction_details);

    if ($stmt->execute()) {
        echo "Details added/updated successfully";
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}

$conn->close();
?>
