<!----------------------------------Login------------------------------------>
<?php
session_start();
include 'php/db_connection.php';

// শুধুমাত্র লগইন করা ইউজার পেজ দেখতে পারবে
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userName = $_SESSION['user_name'];
$role = $_SESSION['role']; // ✅ এখানে role সেভ করা হচ্ছে


$isAdmin = ($_SESSION['role'] == 'admin');

?>


<?php
// Pagination settings
$records_per_page = 10; // প্রতি পেজে কতগুলো রেকর্ড দেখানো হবে
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $records_per_page;

// মোট টাকা হিসাব
$total_tk = 0;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cost_name = $con->real_escape_string($_POST['cost_name']);
    $cost_details = $con->real_escape_string($_POST['cost_details']);
    $tk = $con->real_escape_string($_POST['tk']);

    if (isset($_POST['id']) && !empty($_POST['id'])) {
        // Update existing record
        $id = $con->real_escape_string($_POST['id']);
        $sql = "UPDATE cost SET cost_name='$cost_name', cost_details='$cost_details',  tk='$tk' WHERE id='$id'";
    } else {
        // Insert new record
        $sql = "INSERT INTO cost (cost_name, cost_details, tk) VALUES ('$cost_name', '$cost_details',  '$tk')";
    }

    if ($con->query($sql) === TRUE) {
        echo "Record saved successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $con->error;
    }
}

// Handle deletion
if (isset($_GET['delete_id'])) {
    $delete_id = $con->real_escape_string($_GET['delete_id']);
    $sql = "DELETE FROM cost WHERE id='$delete_id'";
    if ($con->query($sql) === TRUE) {
        echo "Record deleted successfully";
    } else {
        echo "Error deleting record: " . $con->error;
    }
}

// Fetch record for editing
$edit_data = null;
if (isset($_GET['edit_id'])) {
    $edit_id = $con->real_escape_string($_GET['edit_id']);
    $result = $con->query("SELECT * FROM cost WHERE id='$edit_id'");
    if ($result->num_rows > 0) {
        $edit_data = $result->fetch_assoc();
    }
}

// Fetch total amount
$sql_total = "SELECT SUM(tk) as total_tk FROM cost";
$result_total = $con->query($sql_total);
if ($result_total->num_rows > 0) {
    $total_tk = $result_total->fetch_assoc()['total_tk'];
}

// Fetch records with pagination
$sql = "SELECT * FROM cost LIMIT $start, $records_per_page";
$result = $con->query($sql);

// Total records count
$sql_count = "SELECT COUNT(*) as total_records FROM cost";
$result_count = $con->query($sql_count);
$total_records = $result_count->fetch_assoc()['total_records'];

$total_pages = ceil($total_records / $records_per_page);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cost Management</title>
    <link rel="stylesheet" href="css/tbody.css"> <!-- Assuming you have a separate CSS file -->
    <?php include 'sidebar.php'; ?>
    <style>
        /** ==============================পুরান কোড বন্ধ করা হলো---------
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f9;
        }
        .container {
            width: 80%;
            margin: 20px auto;
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
        }
        .form-container {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
            margin-bottom: 20px;
            display: none;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        .form-group textarea {
            resize: none;
            height: 100px;
        }
        .form-group button {
            width: 100%;
            padding: 10px;
            border: none;
            background-color: #28a745;
            color: white;
            font-size: 16px;
            border-radius: 5px;
            cursor: pointer;
        }
        .form-group button:hover {
            background-color: #218838;
        }
       .button{
            color: #c822333;
            padding: 5px 10px;
            border-radius: 5px;
            text-decoration: none;
            cursor: pointer;
        }
        .action-button {
            color: #fff;
            padding: 5px 10px;
            border-radius: 5px;
            text-decoration: none;
            cursor: pointer;
        }
        .delete-button {
            background-color: #dc3545;
        }
        .delete-button:hover {
            background-color: #c82333;
        }
        .edit-button {
            background-color: #007bff;
        }
        .edit-button:hover {
            background-color: #0056b3;
        }
        .pagination {
            text-align: center;
            margin-top: 20px;
        }
        .pagination a {
            display: inline-block;
            padding: 10px 15px;
            margin: 0 5px;
            text-decoration: none;
            color: #007bff;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .pagination a:hover {
            background-color: #f4f4f4;
        }
        .pagination a[style="font-weight:bold;"] {
            font-weight: bold;
            color: #000;
            background-color: #e9ecef;
        }=========================================*/
    </style>
    <script>
        function toggleForm() {
            const formContainer = document.querySelector('.form-container');
            formContainer.style.display = formContainer.style.display === 'none' ? 'block' : 'none';
        }

        function toggleEditForm(editId) {
            const formContainer = document.querySelector('.form-container');
            const editAction = document.querySelector(`a[data-edit-id="${editId}"]`);
            
            if (editAction) {
                formContainer.style.display = formContainer.style.display === 'none' ? 'block' : 'none';
            }
        }
    </script>
</head>
<body>
    <div class="container">
        <h2>Cost Management</h2>
        <button onclick="toggleForm()">Add Cost</button>
        <div class="form-container">
            <form method="POST" action="">
                <input type="hidden" name="id" value="<?php echo $edit_data['id'] ?? ''; ?>">
                <div class="form-group">
                    <label for="cost_name">Name</label>
                    <input type="text" id="cost_name" name="cost_name" value="<?php echo $edit_data['cost_name'] ?? ''; ?>" required>
                </div>
                <div class="form-group">
                    <label for="cost_details">Cost Details</label>
                    <textarea id="cost_details" name="cost_details" required><?php echo $edit_data['cost_details'] ?? ''; ?></textarea>
                </div>
            
                <div class="form-group">
                    <label for="tk">Amount (Tk)</label>
                    <input type="number" id="tk" name="tk" step="0.01" value="<?php echo $edit_data['tk'] ?? ''; ?>" required>
                </div>
                <div class="form-group">
                    <button type="submit">Submit</button>
                </div>
            </form>
        </div>

        <p>Cost Records</p>
        <table>
            <thead>
                <tr>
                    <th>SL No</th>
                    <th>Cost Name</th>
                    <th>Details</th>
                    <th>Amount (Tk)</th>
                    <th colspan="2">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if ($result->num_rows > 0) {
                    $sl_no = $start + 1;
                    while ($row = $result->fetch_assoc()) {
                        echo "<tr>
                                <td>" . $sl_no++ . "</td>
                                <td>" . $row['cost_name'] . "</td>
                                <td>" . $row['cost_details'] . "</td>
                                <td>" . $row['tk'] . "</td>
                                <td>
                                    <a href='?edit_id=" . $row['id'] . "' data-edit-id='" . $row['id'] . "' class='action-button edit-button' onclick='toggleEditForm(" . $row['id'] . ")'><i class='bi bi-pencil-square'></i></a>
                                </td>
                                <td>
                                    <a href='?delete_id=" . $row['id'] . "' class='action-button delete-button'><i class='bi bi-trash'></i></a>
                                </td>
                              </tr>";
                    }
                } else {
                    echo "<tr><td colspan='6'>No records found</td></tr>";
                }
                ?>
            </tbody>
        </table>

        <!-- মোট টাকা -->
        <h3>Total Amount: <?php echo number_format($total_tk, 2); ?> Tk</h3>

        <!-- Pagination -->
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>">Previous</a>
            <?php endif; ?>
            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <a href="?page=<?php echo $i; ?>"<?php if ($i == $page) echo ' style="font-weight:bold;"'; ?>><?php echo $i; ?></a>
            <?php endfor; ?>
            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?>">Next</a>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
