<?php
require_once '../includes/db.php';
require_once '../includes/auth.php';

header('Content-Type: application/json');

if (!hasRole(['owner', 'admin', 'manager'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
    error_log("Machinery API Data: " . print_r($data, true));
    $action = $_GET['action'] ?? $data['action'] ?? '';

    switch ($action) {
        case 'save':
            $id = $data['id'] ?? null;
            $name = $data['name'] ?? '';
            $model_no = $data['model_no'] ?? '';
            $type = $data['type'] ?? '';
            $status = $data['status'] ?? 'Operating';
            $is_active = isset($data['is_active']) ? (int)$data['is_active'] : 1;
            $company_id = $_SESSION['company_id'];

            if (!$name || !$model_no) {
                echo json_encode(['success' => false, 'message' => 'Name and Model Number are required']);
                exit;
            }

            if ($id) {
                query("UPDATE machinery SET name = ?, model_no = ?, type = ?, status = ?, is_active = ?, updated_at = NOW() WHERE id = ? AND company_id = ?", 
                    [$name, $model_no, $type, $status, $is_active, $id, $company_id]);
                echo json_encode(['success' => true, 'message' => 'Machine updated successfully']);
            } else {
                query("INSERT INTO machinery (name, model_no, type, status, is_active, company_id, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())", 
                    [$name, $model_no, $type, $status, $is_active, $company_id]);
                echo json_encode(['success' => true, 'message' => 'Machine added successfully']);
            }
            break;

        case 'delete':
            $id = $data['id'] ?? null;
            $company_id = $_SESSION['company_id'];
            
            if (!$id) {
                echo json_encode(['success' => false, 'message' => 'ID required']);
                exit;
            }

            // Check if machine is in use in line_stages
            $in_use = fetch("SELECT COUNT(*) as count FROM line_stage_machinery WHERE machinery_id = ?", [$id]);
            if ($in_use['count'] > 0) {
                echo json_encode(['success' => false, 'message' => 'Cannot delete machine as it is currently assigned to production lines.']);
                exit;
            }

            query("DELETE FROM machinery WHERE id = ? AND company_id = ?", [$id, $company_id]);
            echo json_encode(['success' => true, 'message' => 'Machine deleted successfully']);
            break;

        case 'toggle-status':
            $id = $data['id'] ?? null;
            $is_active = $data['is_active'] ?? 0;
            $company_id = $_SESSION['company_id'];
            query("UPDATE machinery SET is_active = ? WHERE id = ? AND company_id = ?", [$is_active, $id, $company_id]);
            echo json_encode(['success' => true, 'message' => 'Status updated']);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action: ' . $action]);
            break;
    }
} catch (Exception $e) {
    error_log("Machinery API Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}
