<?php
require_once '../config.php';

$method = $_SERVER['REQUEST_METHOD'];
$pdo = getDBConnection();

switch($method) {
    case 'GET':
        if(isset($_GET['id'])) {
            // Get single object with client info
            $stmt = $pdo->prepare("
                SELECT o.*, c.name as client_name 
                FROM objects o 
                JOIN clients c ON o.client_id = c.client_id 
                WHERE o.object_id = ?
            ");
            $stmt->execute([$_GET['id']]);
            $object = $stmt->fetch();
            echo json_encode($object);
        } else {
            // Get all objects with client info
            $stmt = $pdo->query("
                SELECT o.*, c.name as client_name 
                FROM objects o 
                JOIN clients c ON o.client_id = c.client_id 
                ORDER BY o.object_name
            ");
            $objects = $stmt->fetchAll();
            echo json_encode($objects);
        }
        break;
        
    case 'POST':
        // Create new object
        $data = json_decode(file_get_contents('php://input'), true);
        $stmt = $pdo->prepare("INSERT INTO objects (client_id, object_name, address, contact_person, phone) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $data['client_id'],
            $data['object_name'],
            $data['address'] ?? null,
            $data['contact_person'] ?? null,
            $data['phone'] ?? null
        ]);
        echo json_encode(['id' => $pdo->lastInsertId(), 'message' => 'Object created successfully']);
        break;
        
    case 'PUT':
        // Update object
        $data = json_decode(file_get_contents('php://input'), true);
        $stmt = $pdo->prepare("UPDATE objects SET client_id = ?, object_name = ?, address = ?, contact_person = ?, phone = ? WHERE object_id = ?");
        $stmt->execute([
            $data['client_id'],
            $data['object_name'],
            $data['address'] ?? null,
            $data['contact_person'] ?? null,
            $data['phone'] ?? null,
            $data['id']
        ]);
        echo json_encode(['message' => 'Object updated successfully']);
        break;
        
    case 'DELETE':
        // Delete object
        $data = json_decode(file_get_contents('php://input'), true);
        $stmt = $pdo->prepare("DELETE FROM objects WHERE object_id = ?");
        $stmt->execute([$data['id']]);
        echo json_encode(['message' => 'Object deleted successfully']);
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>

