<?php
session_start();
include 'config.php';  // Your DB connection file

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Log session data
error_log("Holidays Portal - Session data: " . print_r($_SESSION, true), 3, "debug.log");

// Check Superadmin
if (!isset($_SESSION['role']) || strtolower($_SESSION['role']) != 'superadmin') {
    $error_message = "Holidays Portal - Access denied: role=" . ($_SESSION['role'] ?? 'not set');
    error_log($error_message, 3, "debug.log");
    die($error_message);
}

$user_id = $_SESSION['user_id'];

// Handle form submissions
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['action'])) {
    $action = $_POST['action'];
    try {
        if ($action === "add_holiday") {
            $holiday_name = mysqli_real_escape_string($conn, $_POST['holiday_name']);
            $holiday_date = mysqli_real_escape_string($conn, $_POST['holiday_date']);
            $description = mysqli_real_escape_string($conn, $_POST['description']);
            
            $sql = "INSERT INTO holidays (holiday_name, holiday_date, description, created_by) VALUES (?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            $stmt->bind_param("ssss", $holiday_name, $holiday_date, $description, $user_id);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $_SESSION['message'] = "Holiday added successfully.";
            $stmt->close();
        } elseif ($action === "update_holiday") {
            $holiday_id = $_POST['holiday_id'];
            $holiday_name = mysqli_real_escape_string($conn, $_POST['holiday_name']);
            $holiday_date = mysqli_real_escape_string($conn, $_POST['holiday_date']);
            $description = mysqli_real_escape_string($conn, $_POST['description']);
            
            $sql = "UPDATE holidays SET holiday_name = ?, holiday_date = ?, description = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            $stmt->bind_param("sssi", $holiday_name, $holiday_date, $description, $holiday_id);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $_SESSION['message'] = "Holiday updated successfully.";
            $stmt->close();
        } elseif ($action === "delete_holiday") {
            $holiday_id = $_POST['holiday_id'];
            $sql = "DELETE FROM holidays WHERE id = ?";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            $stmt->bind_param("i", $holiday_id);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $_SESSION['message'] = "Holiday deleted successfully.";
            $stmt->close();
        }
    } catch (Exception $e) {
        error_log("Holidays Portal - Error: " . $e->getMessage(), 3, "debug.log");
        $_SESSION['error'] = "Database error: " . $e->getMessage();
    }
    
    // Redirect to avoid form resubmission
    header("Location: holidays.php");
    exit();
}

// Fetch all holidays
$sql = "SELECT * FROM holidays ORDER BY holiday_date ASC";
$result = $conn->query($sql);
if ($result === false) {
    error_log("Holidays Portal - Holidays query error: " . $conn->error, 3, "debug.log");
    $_SESSION['error'] = "Error fetching holidays: " . $conn->error;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Holidays Management - Techknow</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            display: flex;
            min-height: 100vh;
        }
        .sidebar {
            width: 250px;
            background: #2c3e50;
            color: #fff;
            padding: 15px;
            position: fixed;
            top: 0;
            bottom: 0;
            z-index: 1000;
            transform: translateX(-250px);
            transition: transform 0.3s ease;
        }
        .sidebar.active {
            transform: translateX(0);
        }
        .sidebar h2 {
            font-size: 1rem;
            margin-bottom: 15px;
        }
        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 8px 10px;
            display: block;
            border-radius: 4px;
            margin-bottom: 5px;
            font-size: 0.9rem;
        }
        .sidebar a:hover {
            background: #1abc9c;
        }
        .sidebar a.active {
            background: #1abc9c;
        }
        .sidebar .dropdown-menu {
            background: #34495e;
            border: none;
            padding: 0;
        }
        .sidebar .dropdown-menu a {
            color: #fff;
            padding: 8px 20px;
            font-size: 0.85rem;
        }
        .sidebar .dropdown-menu a:hover {
            background: #1abc9c;
        }
        .sidebar .dropdown-toggle::after {
            float: right;
            margin-top: 8px;
        }
        .hamburger {
            position: fixed;
            top: 10px;
            left: 10px;
            z-index: 1100;
            background: #2c3e50;
            color: #fff;
            border: none;
            padding: 8px;
            border-radius: 4px;
            cursor: pointer;
        }
        .content {
            flex: 1;
            padding: 20px;
            margin-left: 0;
            transition: margin-left 0.3s ease;
        }
        .content.active {
            margin-left: 250px;
        }
        h1 {
            font-size: 1.5rem;
            margin-bottom: 20px;
            color: #333;
            text-align: center;
        }
        h2 {
            font-size: 1.2rem;
            color: #2c3e50;
            margin: 20px 0 15px;
        }
        .table {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto 30px;
            border-collapse: collapse;
            background: #fff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            overflow: hidden;
        }
        .table th, .table td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
            font-size: 0.9rem;
        }
        .table th {
            background: #2c3e50;
            color: white;
            font-weight: 600;
        }
        .table tr:nth-child(even) {
            background: #f9f9f9;
        }
        .table tr:hover {
            background: #e8f4f8;
        }
        .form-container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto 30px;
            background: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }
        .form-container input[type="text"],
        .form-container input[type="date"],
        .form-container textarea {
            width: 100%;
            padding: 8px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 0.9rem;
        }
        .form-container textarea {
            height: 100px;
            resize: vertical;
        }
        .form-container button,
        .action-btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
            margin-right: 5px;
        }
        .form-container button {
            background: #1abc9c;
            color: white;
        }
        .action-btn.update {
            background: #3498db;
            color: white;
        }
        .action-btn.delete {
            background: #e74c3c;
            color: white;
        }
        .action-btn:hover {
            opacity: 0.9;
        }
        .card {
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .card-body {
            padding: 20px;
        }
        .table-responsive {
            overflow-x: auto;
        }
        @media (max-width: 576px) {
            .table {
                font-size: 0.75rem;
                display: block;
                overflow-x: auto;
            }
            h1 {
                font-size: 1.2rem;
            }
            h2 {
                font-size: 1rem;
            }
            .form-container input[type="text"],
            .form-container input[type="date"],
            .form-container textarea {
                font-size: 0.75rem;
            }
            .form-container button,
            .action-btn {
                padding: 6px 10px;
                font-size: 0.75rem;
            }
        }
    </style>
</head>
<body>
    <!-- Hamburger Menu -->
    <button class="hamburger" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <h2>Mypeopleconnect</h2>
        <a href="dashboard_admin.php"><i class="fas fa-home"></i> Organisation Chart</a>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" data-bs-toggle="dropdown">
                <i class="fas fa-home"></i> DAP
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="manage_users.php">Employee Details</a></li>
                <li><a class="dropdown-item" href="manage_documents.php">Policies Rolled Out</a></li>
                <li><a class="dropdown-item" href="digital.php">Acceptance Confirmed</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" data-bs-toggle="dropdown">
                <i class="fas fa-users"></i> CAB
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="payroll_dashboard.php">Payroll</a></li>
                <li><a class="dropdown-item" href="leave_dashboard.php">Leave</a></li>
                <li><a class="dropdown-item" href="grievance_dashboard.php">Grievance Portal</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" data-bs-toggle="dropdown">
                <i class="fas fa-user"></i> PEP
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="individual_rr.php">Individual R & R</a></li>
                <li><a class="dropdown-item" href="individual_kpi.php">Individual KPI</a></li>
                <li><a class="dropdown-item active" href="holidays.php">Holidays</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" data-bs-toggle="dropdown">
                <i class="fas fa-book"></i> L&D
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="incident_employee.php">Incident Portal</a></li>
                <li><a class="dropdown-item" href="training_dashboard.php">Training Portal</a></li>
                <li><a class="dropdown-item" href="rr.php">Rewards and Recognition</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" data-bs-toggle="dropdown">
                <i class="fas fa-star"></i> AAA
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="employee_tiy.php">Employee TIY</a></li>
                <li><a class="dropdown-item" href="login_credentials.php">Login Credentials</a></li>
            </ul>
        </div>
        <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <!-- Main Content -->
    <div class="content" id="content">
        <h1 class="text-primary">Holidays Management</h1>

        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($_SESSION['message'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['message']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($_SESSION['error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Add Holiday Form -->
        <div class="card">
            <div class="card-body">
                <h2>Add New Holiday</h2>
                <form method="POST" class="form-container">
                    <input type="hidden" name="action" value="add_holiday">
                    <div class="mb-3">
                        <label for="holiday_name" class="form-label">Holiday Name</label>
                        <input type="text" name="holiday_name" id="holiday_name" class="form-control" placeholder="Enter holiday name" required>
                    </div>
                    <div class="mb-3">
                        <label for="holiday_date" class="form-label">Holiday Date</label>
                        <input type="date" name="holiday_date" id="holiday_date" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea name="description" id="description" class="form-control" placeholder="Enter description"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Add Holiday</button>
                </form>
            </div>
        </div>

        <!-- Holiday List -->
        <div class="card">
            <div class="card-body">
                <h2>Holiday List</h2>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr class="text-center">
                                <th>ID</th>
                                <th>Holiday Name</th>
                                <th>Date</th>
                                <th>Description</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($result && $result->num_rows > 0): ?>
                                <?php while ($row = $result->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'); ?></td>
                                        <td><?php echo htmlspecialchars($row['holiday_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                                        <td><?php echo htmlspecialchars($row['holiday_date'], ENT_QUOTES, 'UTF-8'); ?></td>
                                        <td><?php echo htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8'); ?></td>
                                        <td class="text-center">
                                            <!-- Update Form -->
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="action" value="update_holiday">
                                                <input type="hidden" name="holiday_id" value="<?php echo $row['id']; ?>">
                                                <div class="mb-3">
                                                    <input type="text" name="holiday_name" class="form-control" value="<?php echo htmlspecialchars($row['holiday_name'], ENT_QUOTES, 'UTF-8'); ?>" required>
                                                </div>
                                                <div class="mb-3">
                                                    <input type="date" name="holiday_date" class="form-control" value="<?php echo htmlspecialchars($row['holiday_date'], ENT_QUOTES, 'UTF-8'); ?>" required>
                                                </div>
                                                <div class="mb-3">
                                                    <textarea name="description" class="form-control"><?php echo htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8'); ?></textarea>
                                                </div>
                                                <button type="submit" class="action-btn update">Update</button>
                                            </form>
                                            <!-- Delete Form -->
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="action" value="delete_holiday">
                                                <input type="hidden" name="holiday_id" value="<?php echo $row['id']; ?>">
                                                <button type="submit" class="action-btn delete" onclick="return confirm('Are you sure you want to delete this holiday?');">Delete</button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center text-muted py-4">No holidays found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const content = document.getElementById('content');
            sidebar.classList.toggle('active');
            content.classList.toggle('active');
        }
    </script>
</body>
</html>

<?php $conn->close(); ?>