<?php
/**
 * Pin Control API
 * Manage individual pins (CRUD + Control)
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

require_once '../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $method = $_SERVER['REQUEST_METHOD'];
    
    // GET: List pins for a device
    if ($method === 'GET') {
        $device_id = $_GET['device_id'] ?? null;
        
        if (!$device_id) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id is required']);
            exit;
        }
        
        $query = "SELECT * FROM device_pins WHERE device_id = ? ORDER BY pin_gpio";
        $stmt = $db->prepare($query);
        $stmt->execute([$device_id]);
        $pins = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'pins' => $pins]);
    }
    
    // POST: Add new pin
    elseif ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        
        $device_id = $data['device_id'] ?? '';
        $pin_gpio = $data['pin_gpio'] ?? '';
        $pin_name = $data['pin_name'] ?? '';
        $pin_type = $data['pin_type'] ?? 'relay';
        $pin_location = $data['pin_location'] ?? '';
        $pin_icon = $data['pin_icon'] ?? 'fa-plug';
        
        if (empty($device_id) || empty($pin_gpio) || empty($pin_name)) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields']);
            exit;
        }
        
        // Get next pin number
        $count_query = "SELECT COUNT(*) as count FROM device_pins WHERE device_id = ?";
        $count_stmt = $db->prepare($count_query);
        $count_stmt->execute([$device_id]);
        $count = $count_stmt->fetch(PDO::FETCH_ASSOC)['count'];
        $pin_number = $count + 1;
        
        $query = "INSERT INTO device_pins 
                  (device_id, pin_number, pin_gpio, pin_type, pin_name, pin_location, pin_icon) 
                  VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$device_id, $pin_number, $pin_gpio, $pin_type, $pin_name, $pin_location, $pin_icon])) {
            echo json_encode(['success' => true, 'message' => 'Pin added successfully']);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to add pin']);
        }
    }
    
    // PUT: Update pin
    elseif ($method === 'PUT') {
        $data = json_decode(file_get_contents('php://input'), true);
        
        $pin_id = $data['pin_id'] ?? '';
        $pin_name = $data['pin_name'] ?? '';
        $pin_type = $data['pin_type'] ?? '';
        $pin_location = $data['pin_location'] ?? '';
        $pin_icon = $data['pin_icon'] ?? '';
        
        if (empty($pin_id)) {
            http_response_code(400);
            echo json_encode(['error' => 'pin_id is required']);
            exit;
        }
        
        $query = "UPDATE device_pins 
                  SET pin_name = ?, pin_type = ?, pin_location = ?, pin_icon = ? 
                  WHERE id = ?";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$pin_name, $pin_type, $pin_location, $pin_icon, $pin_id])) {
            echo json_encode(['success' => true, 'message' => 'Pin updated successfully']);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update pin']);
        }
    }
    
    // DELETE: Remove pin
    elseif ($method === 'DELETE') {
        $data = json_decode(file_get_contents('php://input'), true);
        $pin_id = $data['pin_id'] ?? '';
        
        if (empty($pin_id)) {
            http_response_code(400);
            echo json_encode(['error' => 'pin_id is required']);
            exit;
        }
        
        $query = "DELETE FROM device_pins WHERE id = ?";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$pin_id])) {
            echo json_encode(['success' => true, 'message' => 'Pin deleted successfully']);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to delete pin']);
        }
    }
    
    else {
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
