<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Database connection details
$host = "192.168.1.20";
$database = "orologi";
$user = "pdo";
$password = "";

try {
    // Establish a connection to the database
    $connection = new PDO("mysql:host=$host;dbname=$database", $user, $password);
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}

// Handle CRUD operations for Marche
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action == 'add_marca') {
        $marca = $_POST['marca'];
        $nazione = $_POST['nazione'];
        $stmt = $connection->prepare("INSERT INTO marche (marca, nazione) VALUES (:marca, :nazione)");
        $stmt->execute(['marca' => $marca, 'nazione' => $nazione]);
    } elseif ($action == 'delete_marca') {
        $marca = $_POST['marca'];
        $stmt = $connection->prepare("DELETE FROM marche WHERE marca = :marca");
        $stmt->execute(['marca' => $marca]);
    } elseif ($action == 'update_marca') {
        $marca = $_POST['marca'];
        $nazione = $_POST['nazione'];
        $stmt = $connection->prepare("UPDATE marche SET nazione = :nazione WHERE marca = :marca");
        $stmt->execute(['marca' => $marca, 'nazione' => $nazione]);
    }

    // Redirect to avoid form resubmission
    header("Location: dashboard.php");
    exit();
}

// Handle CRUD operations for Orologi
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    $action = $_POST['action'];

    // Handle Marche operations
    if ($action == 'add_marca') {
        $marca = $_POST['marca'];
        $nazione = $_POST['nazione'];
        $stmt = $connection->prepare("INSERT INTO marche (marca, nazione) VALUES (:marca, :nazione)");
        $stmt->execute(['marca' => $marca, 'nazione' => $nazione]);
    } elseif ($action == 'delete_marca') {
        $marca = $_POST['marca'];
        $stmt = $connection->prepare("DELETE FROM marche WHERE marca = :marca");
        $stmt->execute(['marca' => $marca]);
    } elseif ($action == 'update_marca') {
        $marca = $_POST['marca'];
        $nazione = $_POST['nazione'];
        $stmt = $connection->prepare("UPDATE marche SET nazione = :nazione WHERE marca = :marca");
        $stmt->execute(['marca' => $marca, 'nazione' => $nazione]);
    }
    // Handle Orologi operations
    elseif ($action == 'add_orologio') {
        try {
            $marca = $_POST['marca'];
            $modello = $_POST['modello'];
            $prezzo = $_POST['prezzo'];
            $descrizione = $_POST['descrizione'];

            $checkMarca = $connection->prepare("SELECT marca FROM marche WHERE marca = :marca");
            $checkMarca->execute(['marca' => $marca]);
            if (!$checkMarca->fetch()) {
                echo "Error: Brand does not exist in marche table";
                die();
            }
            echo
            $stmt = $connection->prepare("INSERT INTO orologi (Marca, Modello, Prezzo, Descrizione) VALUES (:marca, :modello, :prezzo, :descrizione)");
            $stmt->execute(['marca' => $marca, 'modello' => $modello, 'prezzo' => $prezzo, 'descrizione' => $descrizione]);

            if ($stmt->rowCount() > 0) {
                echo "Insert successful";
            } else {
                echo "Insert failed";
            }
        } catch (PDOException $e) {
            echo "Error: " . $e->getMessage();
            die();
        }
    } elseif ($action == 'delete_orologio') {
        $codice = $_POST['codice'];
        $stmt = $connection->prepare("DELETE FROM orologi WHERE Codice = :codice");
        $stmt->execute(['codice' => $codice]);
    } elseif ($action == 'update_orologio') {
        $codice = $_POST['codice'];
        $marca = $_POST['marca'];
        $modello = $_POST['modello'];
        $prezzo = $_POST['prezzo'];
        $descrizione = $_POST['descrizione'];
        $stmt = $connection->prepare("UPDATE orologi SET Marca = :marca, Modello = :modello, Prezzo = :prezzo, Descrizione = :descrizione WHERE Codice = :codice");
        $stmt->execute(['codice' => $codice, 'marca' => $marca, 'modello' => $modello, 'prezzo' => $prezzo, 'descrizione' => $descrizione]);
    }

    // Single redirect after all operations
    header("Location: dashboard.php");
    exit();
}

// Fetch all Marche and Orologi
$marche = $connection->query("SELECT * FROM marche")->fetchAll(PDO::FETCH_ASSOC);
$orologi = $connection->query("SELECT * FROM orologi")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <link rel="stylesheet" href="https://unpkg.com/@picocss/pico@2/css/pico.min.css">
</head>
<body>
    <main class="container">
        <h1>Admin Dashboard</h1>
        <a href="logout.php" class="button">Logout</a>

        <!-- Marche Section -->
        <h2>Marche</h2>
        <form method="post">
            <input type="hidden" name="action" value="add_marca">
            <label for="marca">Marca:</label>
            <input type="text" id="marca" name="marca" required>
            <label for="nazione">Nazione:</label>
            <input type="text" id="nazione" name="nazione" required>
            <button type="submit">Add Marca</button>
        </form>

        <table>
            <thead>
            <tr>
                <th>Marca</th>
                <th>Nazione</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($marche as $marca): ?>
                <tr>
                    <td><?php echo htmlspecialchars($marca['marca']); ?></td>
                    <td><?php echo htmlspecialchars($marca['nazione']); ?></td>
                    <td>
                        <form method="post" style="display:inline;">
                            <input type="hidden" name="action" value="delete_marca">
                            <input type="hidden" name="marca" value="<?php echo $marca['marca']; ?>">
                            <button type="submit">Delete</button>
                        </form>
                        <form method="post" style="display:inline;">
                            <input type="hidden" name="action" value="update_marca">
                            <input type="hidden" name="marca" value="<?php echo $marca['marca']; ?>">
                            <input type="text" name="nazione" placeholder="New Nazione" required>
                            <button type="submit">Update</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Orologi Section -->
        <h2>Orologi</h2>
        <form method="post">
            <input type="hidden" name="action" value="add_orologio">
            <label for="marca">Marca:</label>
            <select id="marca" name="marca" required>
                <?php foreach ($marche as $marca): ?>
                    <option value="<?php echo $marca['marca']; ?>"><?php echo $marca['marca']; ?></option>
                <?php endforeach; ?>
            </select>
            <label for="modello">Modello:</label>
            <input type="text" id="modello" name="modello" required>
            <label for="prezzo">Prezzo:</label>
            <input type="number" id="prezzo" name="prezzo" required>
            <label for="descrizione">Descrizione:</label>
            <textarea id="descrizione" name="descrizione" required></textarea>
            <button type="submit">Add Orologio</button>
        </form>

        <table>
            <thead>
            <tr>
                <th>Codice</th>
                <th>Marca</th>
                <th>Modello</th>
                <th>Prezzo</th>
                <th>Descrizione</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($orologi as $orologio): ?>
                <tr>
                    <td><?php echo htmlspecialchars($orologio['Codice']); ?></td>
                    <td><?php echo htmlspecialchars($orologio['Marca']); ?></td>
                    <td><?php echo htmlspecialchars($orologio['Modello']); ?></td>
                    <td><?php echo htmlspecialchars($orologio['Prezzo']); ?></td>
                    <td><?php echo htmlspecialchars($orologio['Descrizione']); ?></td>
                    <td>
                        <form method="post" style="display:inline;">
                            <input type="hidden" name="action" value="delete_orologio">
                            <input type="hidden" name="codice" value="<?php echo $orologio['Codice']; ?>">
                            <button type="submit">Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </main>
</body>
</html>