<?php
session_start();
// Database connection
include '../connection.php';

// Check if admin is logged in
if ($_SESSION["admin"] != true) {
    header("location:login.php");
    exit;
}

$message = ""; // Variable to hold messages

// Handle form submission and file upload
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_tender'])) {
    $tender_title = mysqli_real_escape_string($conn, $_POST['tender_title']);
    $tender_date = mysqli_real_escape_string($conn, $_POST['tender_date']);
    $tender_place = mysqli_real_escape_string($conn, $_POST['tender_place']);
    $tender_details = mysqli_real_escape_string($conn, $_POST['tender_details']);
    $status = 1;

    $target_dir = "../uploads/Tenders/";
    $target_file = $target_dir . basename($_FILES["file_location"]["name"]);
    $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    if ($file_type != "pdf") {
        $message = "<p class='error'>Only PDF files are allowed.</p>";
    } elseif ($_FILES["file_location"]["size"] > 10000000) {
        $message = "<p class='error'>File too large (Max 10MB).</p>";
    } else {
        if (move_uploaded_file($_FILES["file_location"]["tmp_name"], $target_file)) {
            $insert_sql = "INSERT INTO tenders (tender_title, tender_date, tender_place, tender_details, file_location, status) 
                           VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("sssssi", $tender_title, $tender_date, $tender_place, $tender_details, $target_file, $status);

            if ($stmt->execute()) {
                $message = "<p class='success'>Tender added successfully.</p>";
                header("Location: " . $_SERVER['PHP_SELF']);
                exit;
            } else {
                $message = "<p class='error'>Error: " . $stmt->error . "</p>";
            }
        } else {
            $message = "<p class='error'>Error uploading file.</p>";
        }
    }
}

// Handle tender deletion
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_id'])) {
    $delete_id = $_POST['delete_id'];
    $select_sql = "SELECT file_location FROM tenders WHERE ID = ?";
    $stmt = $conn->prepare($select_sql);
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        unlink($row['file_location']);
        $delete_sql = "DELETE FROM tenders WHERE ID = ?";
        $stmt = $conn->prepare($delete_sql);
        $stmt->bind_param("i", $delete_id);

        if ($stmt->execute()) {
            $message = "<p class='success'>Tender deleted successfully.</p>";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $message = "<p class='error'>Error deleting tender.</p>";
        }
    }
}

// Retrieve tenders
$sql = "SELECT * FROM tenders";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tender Submission</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f4f4f4;
        }
        form {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
        }
        input, textarea, select {
            width: 100%;
            padding: 10px;
            margin: 5px 0;
        }
        .success { color: green; }
        .error { color: red; }
        .progress-container { width: 100%; background: #ddd; border-radius: 8px; }
        .progress-bar { width: 0%; height: 20px; background: green; border-radius: 8px; }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 10px;
            border: 1px solid #ccc;
        }
        th {
            background: #333;
            color: white;
        }
        button {
            padding: 8px 12px;
            background: red;
            color: white;
            border: none;
            cursor: pointer;
        }
    </style>
    <script>
        function updateProgress(e) {
            if (e.lengthComputable) {
                var percent = (e.loaded / e.total) * 100;
                document.getElementById("progress-bar").style.width = percent + "%";
            }
        }
        function startUpload() {
            document.getElementById("progress-container").style.display = "block";
        }
    </script>
</head>
<body>

<h2>Submit Tender</h2>
<form action="" method="post" enctype="multipart/form-data" onsubmit="startUpload()">
    <label for="tender_title">Title:</label>
    <input type="text" id="tender_title" name="tender_title" required>

    <label for="tender_date">Date:</label>
    <input type="date" id="tender_date" name="tender_date" required>

    <label for="tender_place">Place:</label>
    <input type="text" id="tender_place" name="tender_place" required>

    <label for="tender_details">Details:</label>
    <textarea id="tender_details" name="tender_details" required></textarea>

    <label for="file_location">Upload PDF:</label>
    <input type="file" id="file_location" name="file_location" accept=".pdf" required>

    <div id="progress-container" class="progress-container" style="display:none;">
        <div id="progress-bar" class="progress-bar"></div>
    </div>

    <input type="submit" name="submit_tender" value="Submit">
</form>

<?php echo $message; ?>

<h2>Tender List</h2>
<table>
    <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Date</th>
        <th>Place</th>
        <th>Details</th>
        <th>File</th>
        <th>Actions</th>
    </tr>
    <?php while ($row = $result->fetch_assoc()) { ?>
    <tr>
        <td><?= $row['ID'] ?></td>
        <td><?= $row['tender_title'] ?></td>
        <td><?= $row['tender_date'] ?></td>
        <td><?= $row['tender_place'] ?></td>
        <td><?= $row['tender_details'] ?></td>
        <td><a href="<?= $row['file_location'] ?>" target="_blank">View PDF</a></td>
        <td>
            <form method="post">
                <input type="hidden" name="delete_id" value="<?= $row['ID'] ?>">
                <button type="submit">Delete</button>
            </form>
        </td>
    </tr>
    <?php } ?>
</table>

</body>
</html>