<?php
// register_serial.php
// Simple script to register serial numbers

// Create Auth_devices directory if it doesn't exist
$authDir = __DIR__ . '/Auth_devices';
if (!is_dir($authDir)) {
    if (!mkdir($authDir, 0755, true)) {
        die("Error: Could not create Auth_devices directory");
    }
}

// Path to devices.json file
$devicesFile = $authDir . '/devices.json';

// Initialize devices array
$devices = [];

// Load existing devices if file exists
if (file_exists($devicesFile)) {
    $jsonContent = file_get_contents($devicesFile);
    if ($jsonContent !== false) {
        $devices = json_decode($jsonContent, true) ?: [];
    }
}

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $serial = isset($_POST['serial']) ? trim($_POST['serial']) : '';
    
    if (empty($serial)) {
        $message = "Error: Please enter a serial number";
        $messageType = "error";
    } else {
        // Check if serial already exists
        $serialExists = false;
        foreach ($devices as $device) {
            if (isset($device['serial']) && $device['serial'] === $serial) {
                $serialExists = true;
                break;
            }
        }
        
        if ($serialExists) {
            $message = "Error: Serial number '$serial' is already registered";
            $messageType = "error";
        } else {
            // Add new serial with timestamp
            $newDevice = [
                'serial' => $serial,
                'registered_at' => date('Y-m-d H:i:s'),
                'id' => uniqid()
            ];
            
            $devices[] = $newDevice;
            
            // Save to file
            if (file_put_contents($devicesFile, json_encode($devices, JSON_PRETTY_PRINT))) {
                $message = "Success: Serial number '$serial' has been registered successfully!";
                $messageType = "success";
            } else {
                $message = "Error: Could not save serial number";
                $messageType = "error";
            }
        }
    }
}

// Check if delete action was requested via GET
if (isset($_GET['delete'])) {
    $deleteSerial = $_GET['delete'];
    $newDevices = [];
    $deleted = false;
    
    foreach ($devices as $device) {
        if (isset($device['serial']) && $device['serial'] === $deleteSerial) {
            $deleted = true;
            continue; // Skip this one (delete it)
        }
        $newDevices[] = $device;
    }
    
    if ($deleted) {
        $devices = $newDevices;
        if (file_put_contents($devicesFile, json_encode($devices, JSON_PRETTY_PRINT))) {
            $message = "Success: Serial number '$deleteSerial' has been deleted";
            $messageType = "success";
        } else {
            $message = "Error: Could not delete serial number";
            $messageType = "error";
        }
    } else {
        $message = "Error: Serial number '$deleteSerial' not found";
        $messageType = "error";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register Serial Number</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"] {
            width: 100%;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .message {
            padding: 10px;
            margin: 20px 0;
            border-radius: 5px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .devices-list {
            margin-top: 30px;
        }
        .device-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .delete-btn {
            background-color: #dc3545;
            color: white;
            padding: 5px 10px;
            text-decoration: none;
            border-radius: 3px;
            font-size: 12px;
        }
        .delete-btn:hover {
            background-color: #c82333;
        }
        h1, h2 {
            color: #333;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Register Serial Number</h1>
        
        <?php if (isset($message)): ?>
            <div class="message <?php echo $messageType; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <div class="form-group">
            <form method="POST">
                <label for="serial">Serial Number:</label>
                <input type="text" id="serial" name="serial" required 
                       placeholder="Enter device serial number">
                <button type="submit">Register Serial</button>
            </form>
        </div>

        <div class="devices-list">
            <h2>Registered Devices (<?php echo count($devices); ?>)</h2>
            
            <?php if (empty($devices)): ?>
                <p>No serial numbers registered yet.</p>
            <?php else: ?>
                <?php foreach ($devices as $device): ?>
                    <div class="device-item">
                        <div>
                            <strong><?php echo htmlspecialchars($device['serial']); ?></strong>
                            <?php if (isset($device['registered_at'])): ?>
                                <br><small>Registered: <?php echo htmlspecialchars($device['registered_at']); ?></small>
                            <?php endif; ?>
                        </div>
                        <a href="?delete=<?php echo urlencode($device['serial']); ?>" 
                           class="delete-btn" 
                           onclick="return confirm('Are you sure yelete serial <?php echo htmlspecialchars($device['serial']); ?>?')">
                            Delete
                        </a>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <div style="margin-top: 30px; padding: 15px; background-color: #f8f9fa; border-radius: 5px;">
            <h3>API Usage</h3>
            <p>Use the following URL format to check authorization:</p>
            <code>https://itouchcoderemoval.in/server13/?model=iPhoneModel&amp;serial=SERIAL_NUMBER</code>
        </div>
    </div>
</body>
</html>