<?php
include '../includes/connection.php';
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['mpid']) || $_SESSION['mpid'] !== 1) {
    header("Location: http://localhost/LoanApprovalPredction/admin.php");
    exit();
}

// Handle delete request
if (isset($_GET['delete'])) {
    $nid = intval($_GET['delete']);

    // Fetch image filename
    $getImgQuery = "SELECT img FROM notification WHERE nid = $nid";
    $imgResult = mysqli_query($conn, $getImgQuery);
    if ($imgResult && mysqli_num_rows($imgResult) > 0) {
        $imgRow = mysqli_fetch_assoc($imgResult);
        $imgPath = 'notificationimg/' . $imgRow['img'];
        if (!empty($imgRow['img']) && file_exists($imgPath)) {
            unlink($imgPath); // Delete image file
        }
    }

    // Delete from database
    $delQuery = "DELETE FROM notification WHERE nid = $nid";
    if (mysqli_query($conn, $delQuery)) {
        $_SESSION['dn'] = "<script>alert('Notification deleted successfully.')</script>";
    } else {
        $_SESSION['dn'] = "<script>alert('Failed to delete notification.')</script>";
    }

    header("Location: notification.php");
    exit();
}

// Show messages
if (isset($_SESSION['notification'])) {
    echo $_SESSION['notification'];
    unset($_SESSION['notification']);
}
if (isset($_SESSION['dn'])) {
    echo $_SESSION['dn'];
    unset($_SESSION['dn']);
}
$name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($name); ?> - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <header class="sticky top-0 z-50 bg-white shadow-sm">
        <?php include '../includes/newnavbar.php'; ?>
    </header>

    <main class="container mx-auto px-4 py-8">
        <!-- Notification Form -->
        <section class="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 class="text-2xl font-semibold text-gray-800 mb-6">Create Notification</h2>
            <form class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
                <div>
                    <label for="notification" class="block text-sm font-medium text-gray-700">Message</label>
                    <input type="text" name="notification" id="notification" class="mt-1 w-full h-10 px-3 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500" placeholder="Write your message or notification" required>
                </div>
                <div>
                    <label for="to" class="block text-sm font-medium text-gray-700">Recipient</label>
                    <?php 
                    $sql = "SELECT * FROM position"; 
                    $result = mysqli_query($conn, $sql);
                    if (mysqli_num_rows($result) > 0) {
                    ?>
                    <select name="to" id="to" class="mt-1 w-full h-10 px-3 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white" required>
                        <option value="" disabled selected>Select recipient</option>
                        <?php while ($rows = mysqli_fetch_assoc($result)) { ?>
                            <option value="<?php echo $rows['Pid']; ?>"><?php echo htmlspecialchars($rows['Position']); ?></option>
                        <?php } ?>
                    </select>
                    <?php } ?>
                </div>
                <div>
                    <label for="photo" class="block text-sm font-medium text-gray-700">Image</label>
                    <input type="file" name="photo" id="photo" accept="image/*" class="mt-1 w-full h-10 px-3 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100">
                </div>
                <div>
                    <input type="submit" name="submit" value="Submit" class="w-full h-10 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 transition duration-200 cursor-pointer">
                </div>
            </form>
        </section>

        <!-- Notifications List -->
        <section class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-2xl font-semibold text-gray-800 mb-6">Notifications</h2>
            <?php 
            $sn = "SELECT notification.nid, notification.notification, notification.MPid, notification.date, notification.img, position.Pid, position.Position 
                   FROM notification INNER JOIN position ON notification.MPid = position.Pid";
            $rn = mysqli_query($conn, $sn);
            if (mysqli_num_rows($rn) > 0) {
            ?>
            <div class="grid gap-4">
                <?php while ($nr = mysqli_fetch_assoc($rn)) { ?>
                <div class="flex flex-col md:flex-row items-center justify-between gap-4 p-4 bg-gray-50 rounded-md shadow-sm hover:shadow-md transition duration-200">
                    <div class="flex items-center gap-4">
                        <?php 
                        $imagePath = 'notificationimg/' . htmlspecialchars($nr['img']);
                        if (!empty($nr['img']) && file_exists($imagePath)) { ?>
                            <img src="<?php echo $imagePath; ?>" alt="Notification Image" class="h-16 w-16 object-cover rounded-full">
                        <?php } else { ?>
                            <div class="h-16 w-16 bg-gray-200 rounded-full flex items-center justify-center text-gray-500">No Image</div>
                        <?php } ?>
                        <div>
                            <p class="text-gray-800 font-medium"><?php echo htmlspecialchars($nr['notification']); ?></p>
                            <p class="text-sm text-gray-500">To: <?php echo htmlspecialchars($nr['Position']); ?> | <?php echo date('M d, Y', strtotime($nr['date'])); ?></p>
                        </div>
                    </div>
                    <a href="notification.php?delete=<?php echo $nr['nid']; ?>" onclick="return confirm('Are you sure you want to delete this notification?');" class="text-red-600 hover:text-red-800 font-medium">Delete</a>
                </div>
                <?php } ?>
            </div>
            <?php } else { ?>
                <p class="text-gray-500 text-center">No notifications found.</p>
            <?php } ?>
        </section>
    </main>
</body>
</html>

<?php 
if (isset($_REQUEST['submit'])) {
    $name = '';
    $uploadOk = 1;
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
        $targetDir = "notificationimg/";
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0755, true);
        }
        $name = basename($_FILES['photo']['name']);
        $targetFile = $targetDir . $name;
        $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        
        $check = getimagesize($_FILES['photo']['tmp_name']);
        if ($check === false) {
            echo "<script>alert('File is not an image.')</script>";
            $uploadOk = 0;
        }
        
        if ($_FILES['photo']['size'] > 5000000) {
            echo "<script>alert('File is too large.')</script>";
            $uploadOk = 0;
        }
        
        if (!in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif'])) {
            echo "<script>alert('Only JPG, JPEG, PNG & GIF files are allowed.')</script>";
            $uploadOk = 0;
        }
        
        if ($uploadOk && !move_uploaded_file($_FILES['photo']['tmp_name'], $targetFile)) {
            echo "<script>alert('Error uploading file.')</script>";
            $uploadOk = 0;
        }
    }
    
    if ($uploadOk) {
        $date = date('Y-m-d');
        $notification = mysqli_real_escape_string($conn, $_REQUEST['notification']);
        $to = $_REQUEST['to'];
        $sql12 = "INSERT INTO `notification` (`notification`, `MPid`, `date`, `img`) VALUES ('$notification', '$to', '$date', '$name')";
        if (mysqli_query($conn, $sql12)) {
            $_SESSION['notification'] = "<script>alert('Message or Notification added successfully')</script>";
            echo "<script>window.location.href='notification.php'</script>";
        } else {
            echo "<script>alert('Error adding notification: " . mysqli_error($conn) . "')</script>";
        }
    }
}
?>
