<?php
// Start session and include necessary files
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/Classifications.php'; // New Classifications class

// Redirect if not logged in or not a DAC Staff
redirect_if_not_logged_in('../index.php');
redirect_if_not_role('DAC Staff', '../index.php');

// Initialize Classifications class
$classification = new Classifications($pdo);

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'] ?? ''; // 'datatype' or 'category'
    $action_type = $_POST['action_type'] ?? ''; // 'add' or 'edit'
    $name_en = trim($_POST['name_en'] ?? '');
    $name_kh = trim($_POST['name_kh'] ?? '');
    $details = trim($_POST['details'] ?? '');
    $record_id = $_POST['record_id'] ?? null;

    if (empty($name_en)) {
        set_message('English name cannot be empty.', 'danger');
        header('Location: manage_classifications.php');
        exit();
    }

    try {
        if ($type === 'datatype') {
            if ($action_type === 'add') {
                $classification->addDataType($name_en, $name_kh, $_SESSION['user_id']);
                set_message('Data Type added successfully!', 'success');
            } elseif ($action_type === 'edit' && $record_id) {
                $classification->updateDataType($record_id, $name_en, $name_kh, $_SESSION['user_id']);
                set_message('Data Type updated successfully!', 'success');
            } elseif ($action_type === 'delete' && $record_id) {
                $classification->deleteDataType($record_id);
                set_message('Data Type deleted successfully!', 'success');
            }
        } elseif ($type === 'category') {
            if ($action_type === 'add') {
                $classification->addCategory($name_en, $details, $_SESSION['user_id']);
                set_message('Category added successfully!', 'success');
            } elseif ($action_type === 'edit' && $record_id) {
                $classification->updateCategory($record_id, $name_en, $details, $_SESSION['user_id']);
                set_message('Category updated successfully!', 'success');
            } elseif ($action_type === 'delete' && $record_id) {
                $classification->deleteCategory($record_id);
                set_message('Category deleted successfully!', 'success');
            }
        }
    } catch (Exception $e) {
        set_message('Error: ' . $e->getMessage(), 'danger');
    }
    header('Location: manage_classifications.php');
    exit();
}

// Fetch data for display
$dataTypes = $classification->getAllDataTypes();
$categories = $classification->getAllCategories();

// Prepare data for editing if action is 'edit'
$editDataType = null;
$editCategory = null;
if ($action === 'edit' && $id) {
    if ($_GET['type'] === 'datatype') {
        $editDataType = $classification->getDataTypeById($id);
    } elseif ($_GET['type'] === 'category') {
        $editCategory = $classification->getCategoryById($id);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_admin.php");
?>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_admin.php");
        ?>

        <!-- Main Content -->
        <div class="main-content">
            <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 rounded-3">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Manage Classifications</a>
                    <div class="d-flex">
                        <span class="navbar-text me-3">
                            Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!
                        </span>
                    </div>
                </div>
            </nav>

            <?php
            // Display session messages
            if (isset($_SESSION['message'])) {
                echo '<div class="alert alert-' . $_SESSION['message_type'] . ' alert-dismissible fade show rounded" role="alert">' . htmlspecialchars($_SESSION['message']) . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
                unset($_SESSION['message']);
                unset($_SESSION['message_type']);
            }
            ?>

            <!-- Data Type Management -->
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">Manage Data Types</h5>
                </div>
                <div class="card-body">
                    <form action="manage_classifications.php" method="POST" class="mb-4">
                        <input type="hidden" name="type" value="datatype">
                        <input type="hidden" name="action_type" value="<?php echo $editDataType ? 'edit' : 'add'; ?>">
                        <?php if ($editDataType): ?>
                            <input type="hidden" name="record_id" value="<?php echo htmlspecialchars($editDataType['pkdspstds_id']); ?>">
                        <?php endif; ?>
                        <div class="row g-3 align-items-end">
                            <div class="col-md-5">
                                <label for="dataTypeNameEn" class="form-label">Data Type Name (English)</label>
                                <input type="text" class="form-control rounded" id="dataTypeNameEn" name="name_en" value="<?php echo htmlspecialchars($editDataType['dspstds_name_en'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-5">
                                <label for="dataTypeNameKh" class="form-label">Data Type Name (Khmer)</label>
                                <input type="text" class="form-control rounded" id="dataTypeNameKh" name="name_kh" value="<?php echo htmlspecialchars($editDataType['dspstds_name_kh'] ?? ''); ?>">
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-primary w-100 rounded">
                                    <i class="fas fa-<?php echo $editDataType ? 'save' : 'plus'; ?> me-2"></i> <?php echo $editDataType ? 'Update' : 'Add'; ?> Data Type
                                </button>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>English Name</th>
                                    <th>Khmer Name</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($dataTypes)): ?>
                                    <?php foreach ($dataTypes as $dataType): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($dataType['pkdspstds_id']); ?></td>
                                            <td><?php echo htmlspecialchars($dataType['dspstds_name_en']); ?></td>
                                            <td><?php echo htmlspecialchars($dataType['dspstds_name_kh']); ?></td>
                                            <td>
                                                <a href="manage_classifications.php?action=edit&type=datatype&id=<?php echo htmlspecialchars($dataType['pkdspstds_id']); ?>" class="btn btn-sm btn-warning rounded btn-action">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <form action="manage_classifications.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this Data Type?');">
                                                    <input type="hidden" name="type" value="datatype">
                                                    <input type="hidden" name="action_type" value="delete">
                                                    <input type="hidden" name="record_id" value="<?php echo htmlspecialchars($dataType['pkdspstds_id']); ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger rounded btn-action">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="4" class="text-center">No data types found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Category Management -->
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">Manage Categories</h5>
                </div>
                <div class="card-body">
                    <form action="manage_classifications.php" method="POST" class="mb-4">
                        <input type="hidden" name="type" value="category">
                        <input type="hidden" name="action_type" value="<?php echo $editCategory ? 'edit' : 'add'; ?>">
                        <?php if ($editCategory): ?>
                            <input type="hidden" name="record_id" value="<?php echo htmlspecialchars($editCategory['pkdspscate_id']); ?>">
                        <?php endif; ?>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="categoryTitleEn" class="form-label">Category Title (English)</label>
                                <input type="text" class="form-control rounded" id="categoryTitleEn" name="name_en" value="<?php echo htmlspecialchars($editCategory['dspscate_title_en'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label for="categoryDetails" class="form-label">Details</label>
                                <textarea class="form-control rounded-3" id="categoryDetails" name="details" rows="3"><?php echo htmlspecialchars($editCategory['dspscate_details'] ?? ''); ?></textarea>
                            </div>
                            <div class="col-12">
                                <button type="submit" class="btn btn-success rounded">
                                    <i class="fas fa-<?php echo $editCategory ? 'save' : 'plus'; ?> me-2"></i> <?php echo $editCategory ? 'Update' : 'Add'; ?> Category
                                </button>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>English Title</th>
                                    <th>Details</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($categories)): ?>
                                    <?php foreach ($categories as $category): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($category['pkdspscate_id']); ?></td>
                                            <td><?php echo htmlspecialchars($category['dspscate_title_en']); ?></td>
                                            <td><?php echo htmlspecialchars($category['dspscate_details']); ?></td>
                                            <td>
                                                <a href="manage_classifications.php?action=edit&type=category&id=<?php echo htmlspecialchars($category['pkdspscate_id']); ?>" class="btn btn-sm btn-warning rounded btn-action">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <form action="manage_classifications.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this Category?');">
                                                    <input type="hidden" name="type" value="category">
                                                    <input type="hidden" name="action_type" value="delete">
                                                    <input type="hidden" name="record_id" value="<?php echo htmlspecialchars($category['pkdspscate_id']); ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger rounded btn-action">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="4" class="text-center">No categories found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <?php
    // Include Footer file for owner pages
    include_once("../includes/footer_admin.php");
    ?>  
</body>
</html>
