<?php
$conn = new mysqli('localhost', 'papino', '??', 'ulikequicknote');

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$action = $_GET['action'] ?? '';

switch ($action) {
    case 'fetch':
        $page = $_GET['page'] ?? 1;
        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        $result = $conn->query("SELECT * FROM notes ORDER BY created_at DESC LIMIT $offset, $perPage");
        $notes = [];

        while ($row = $result->fetch_assoc()) {
            $notes[] = $row;
        }

        $totalRows = $conn->query("SELECT COUNT(*) AS count FROM notes")->fetch_assoc()['count'];
        $totalPages = ceil($totalRows / $perPage);

        echo json_encode(['notes' => $notes, 'totalPages' => $totalPages]);

        break;


    case 'add':
        $data = json_decode(file_get_contents('php://input'), true);
        $mmdd = $data['mmdd'];
        $obj = $data['obj'];
        $more = $data['more'];
        $details = $data['details'];
        $archived = 0; // Ensure archived is set to 0 for new notes

        $stmt = $conn->prepare("INSERT INTO notes (mmdd, obj, more, details, archived) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param('ssssi', $mmdd, $obj, $more, $details, $archived);
        $success = $stmt->execute();

        echo json_encode(['success' => $success]);

        break;

    case 'delete':
        $id = $_GET['id'];
        $stmt = $conn->prepare("DELETE FROM notes WHERE id = ?");
        $stmt->bind_param('i', $id);
        $success = $stmt->execute();

        echo json_encode(['success' => $success]);

        break;

    case 'archive':
        $id = $_GET['id'];
        $note = $conn->query("SELECT * FROM notes WHERE id = $id")->fetch_assoc();
        $archivedNote = "{$note['mmdd']}: {$note['obj']} {$note['more']} * {$note['details']}\n";
        file_put_contents('archivednote.txt', $archivedNote, FILE_APPEND);

        $stmt = $conn->prepare("UPDATE notes SET archived = 1 WHERE id = ?");
        $stmt->bind_param('i', $id);
        $success = $stmt->execute();

        echo json_encode(['success' => $success]);

        break;

    case 'fetchSingle':
        $id = $_GET['id'];
        $note = $conn->query("SELECT * FROM notes WHERE id = $id")->fetch_assoc();
        echo json_encode($note);
        break;

    case 'edit':
        $id = $_GET['id'];
        $data = json_decode(file_get_contents('php://input'), true);
        $obj = $data['obj'];
        $more = $data['more'];
        $details = $data['details'];
        $archived = 0; // Reset archived status when editing

        $stmt = $conn->prepare("UPDATE notes SET obj = ?, more = ?, details = ?, archived = ? WHERE id = ?");
        $stmt->bind_param('sssii', $obj, $more, $details, $archived, $id);
        $success = $stmt->execute();

        echo json_encode(['success' => $success]);

        break;
}

$conn->close();
?>