
<?php
ob_start();
include("connection.php");

// Add new facility
if(isset($_POST['add_facility'])) {
    $facility_name = mysqli_real_escape_string($conn, $_POST['facility_name']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    
    // Handle file upload - check if file is uploaded
    $fileName = '';
    if(isset($_FILES["image"]) && $_FILES["image"]["error"] == 0 && !empty($_FILES["image"]["name"])) {
        $targetDir = "facility_images/";
        $fileName = time() . "_" . basename($_FILES["image"]["name"]);
        $targetFile = $targetDir . $fileName;
        $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        $allowedTypes = ['jpg','jpeg','png','gif'];
        
        if(in_array($imageFileType,$allowedTypes)) {
            if(!move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
                $fileName = ''; // Reset if upload fails
            }
        } else {
            $fileName = ''; // Reset if file type not allowed
        }
    }
    
    $created_at = date('Y-m-d H:i:s');

    // Insert facility
    $sql = mysqli_query($conn, "
        INSERT INTO `facilities`(`facility_name`, `description`, `image`, `created_at`)
        VALUES ('$facility_name','$description','$fileName','$created_at')
    ");

    if($sql) {
        echo "Facility added successfully!";
    } else {
        echo "Error: " . mysqli_error($conn);
    }
}

// Fetch facility data for edit
if(isset($_POST['fetch_facility'])) {
    $facility_id = mysqli_real_escape_string($conn, $_POST['facility_id']);
    $q = mysqli_query($conn,"
        SELECT * FROM facilities 
        WHERE id='$facility_id'
        ORDER BY id ASC limit 1
    ");
    $data = mysqli_fetch_assoc($q);
    
    echo json_encode([
        "id"            => $data['id'],
        "facility_name" => $data['facility_name'],
        "description"   => $data['description'],
        "image"         => $data['image']
    ]);
    exit;
}

// Edit facility details
if(isset($_POST['edit_facility'])) {
    $facility_id = mysqli_real_escape_string($conn, $_POST['id']);
    $facility_name = mysqli_real_escape_string($conn, $_POST['facility_name']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    
    // Handle file upload - check if file is uploaded
    $fileName = '';
    if(isset($_FILES["image"]) && $_FILES["image"]["error"] == 0 && !empty($_FILES["image"]["name"])) {
        $targetDir = "facility_images/";
        $fileName = time() . "_" . basename($_FILES["image"]["name"]);
        $targetFile = $targetDir . $fileName;
        $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        $allowedTypes = ['jpg','jpeg','png','gif'];
        
        if(in_array($imageFileType,$allowedTypes)) {
            if(!move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
                $fileName = ''; // Reset if upload fails
            }
        } else {
            $fileName = ''; // Reset if file type not allowed
        }
    }

    // Update facility
    $sql = mysqli_query($conn, "
        UPDATE `facilities` SET 
        `facility_name`='$facility_name',
        `description`='$description'
        WHERE `id`='$facility_id'
    ");
    
    if($fileName != '') {
        $sql = mysqli_query($conn, "
            UPDATE `facilities` SET `image`='$fileName' WHERE `id`='$facility_id'
        ");
    }

    if ($sql) {
        if (mysqli_affected_rows($conn) > 0) {
            echo "Facility updated successfully!";
        } else {
            echo "No changes made to facility data.";
        }
    } else {
        echo "Error updating facility: " . mysqli_error($conn);
    }
}

// Delete facility
if(isset($_POST['delete_facility'])) {
    $facility_id = mysqli_real_escape_string($conn, $_POST['facility_id']);
    $q = mysqli_query($conn,"
        DELETE FROM `facilities` WHERE `id`='$facility_id'
    ");
    if($q) {
        echo "Facility deleted successfully!";
    } else {
        echo "Error deleting facility: " . mysqli_error($conn);
    }
    exit;
}
?>
