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

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

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

