<?php
session_start();
// Check if the user is logged in and if they have the correct role
if (!isset($_SESSION['username']) || ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'manager')) {
    header("Location: staff_owings.php");
    exit();
}
include '../config/db.php';

// Initialize filters
$today = date('Y-m-d');
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : $today;
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : $today;
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$username_filter = isset($_GET['username']) ? $_GET['username'] : '';

// Build the base query
$sql = "SELECT * FROM owings WHERE 1=1";
$params = [];

// Apply filters
if (!isset($_GET['filter']) || $_GET['filter'] !== 'all_time') {
    $sql .= " AND DATE(created_at) BETWEEN :start_date AND :end_date";
    $params[':start_date'] = $start_date;
    $params[':end_date'] = $end_date;
}

if ($status_filter !== 'all') {
    $sql .= " AND status = :status";
    $params[':status'] = $status_filter;
}

if (!empty($username_filter)) {
    $sql .= " AND person_name LIKE :username";
    $params[':username'] = "%$username_filter%";
}

$sql .= " ORDER BY created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$owings = $stmt->fetchAll();

$total_owed_to_me = 0; // Total for "Owed to Me"
$total_i_owe = 0;      // Total for "I Owe"

foreach ($owings as $owing):
    // Check the status to include only "Owing" records
    if ($owing['status'] === 'owing') {
        if ($owing['owing_type'] === 'owed_to_me') {
            $total_owed_to_me += $owing['amount'];
        } elseif ($owing['owing_type'] === 'i_owe') {
            $total_i_owe += $owing['amount'];
        }
    }
endforeach;
// Fetch pharmacy name from the settings table
$query = "SELECT pharmacy_name FROM settings LIMIT 1"; // Assuming only one entry
$stmt = $pdo->prepare($query);
$stmt->execute();
$setting = $stmt->fetch(PDO::FETCH_ASSOC);
$pharmacy_name = $setting['pharmacy_name'] ?? 'Default Pharmacy Name'; // Fallback to a default if not found

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Owing Management - Store Management</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    
    <style>
        :root {
            --primary-color: #2c3e50;
            --border-color: #dee2e6;
            --text-color: #333333;
            --background-color: #f8f9fa;
        }

        body {
            background-color: var(--background-color);
            font-family: 'Mulish', sans-serif;
            color: var(--text-color);
        }

        .content {
            margin-left: 240px;
            padding: 20px;
        }

        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .owing-card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            padding: 20px;
        }

        .summary-card {
            background: var(--primary-color);
            color: white;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }

        .table thead th {
            background-color: var(--primary-color);
            color: white;
        }

        .badge-owing {
            background-color: #dc3545;
            color: white;
        }

        .badge-paid {
            background-color: #28a745;
            color: white;
        }

        .btn-toggle {
            border: 1px solid var(--primary-color);
            background: none;
            color: var(--primary-color);
            padding: 5px 15px;
        }

        .btn-toggle.active {
            background: var(--primary-color);
            color: white;
        }

        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 10px;
            }
        }

        /* Add these to your existing styles */
        .form-control[type="date"] {
            width: auto;
        }

        .btn-group .btn-outline-primary {
            font-size: 0.875rem;
            padding: 0.25rem 0.5rem;
        }

        .quick-filters {
            display: flex;
            gap: 0.5rem;
            align-items: center;
        }

        @media (max-width: 768px) {
            .d-flex.gap-2 {
                flex-wrap: wrap;
            }
            
            .form-control[type="date"] {
                width: 100%;
            }
            
            .btn-group {
                width: 100%;
                margin-top: 0.5rem;
            }
        }

        /* Add to your existing styles */
        .filter-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 4px;
            border: 1px solid var(--border-color);
        }

        .input-group-text {
            background: white;
            border-right: none;
        }

        .input-group .form-control {
            border-left: none;
        }

        .input-group .form-control:focus {
            border-left: none;
            box-shadow: none;
        }

        .quick-filters .btn {
            position: relative;
            transition: all 0.2s;
        }

        .quick-filters .btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .custom-date-range {
            flex: 1;
            min-width: 300px;
        }

        .summary-card {
            position: relative;
            overflow: hidden;
        }

        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: rgba(255, 255, 255, 0.2);
        }

        .badge {
            padding: 0.5em 0.8em;
            border-radius: 30px;
            font-weight: 500;
        }

        .table td {
            vertical-align: middle;
        }

        @media (max-width: 768px) {
            .custom-date-range {
                width: 100%;
                margin-top: 1rem;
            }
            
            .quick-filters {
                width: 100%;
                overflow-x: auto;
            }
        }
    </style>
</head>
<body>
    <?php include '../includes/side_bar.php'; ?>

    <div class="content">
        <div class="top-bar">
            <div class="d-flex justify-content-between align-items-center">
                <h4 class="mb-0">Owing Management</h4>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addOwingModal">
                    <i class="fas fa-plus"></i> Add New Owing
                </button>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="summary-card">
                    <h6>Total Owed to Me</h6>
                    <h3 class="mb-0">₦<span id="totalOwedToMe">0.00</span></h3>
                </div>
            </div>
            <div class="col-md-6">
                <div class="summary-card">
                    <h6>Total I Owe</h6>
                    <h3 class="mb-0">₦<span id="totalIOwe">0.00</span></h3>
                </div>
            </div>
        </div>

        <div class="owing-card">
    <div class="filter-section mb-4">
        <form method="GET" class="row g-3" id="dateFilterForm">
            <!-- Search and Status Row -->
            <div class="col-md-6">
                <div class="input-group">
                    <span class="input-group-text">
                        <i class="fas fa-search"></i>
                    </span>
                    <input type="text" name="username" class="form-control" 
                           placeholder="Search by name" 
                           value="<?= htmlspecialchars($username_filter) ?>">
                </div>
            </div>
            <div class="col-md-6">
                <div class="input-group">
                    <span class="input-group-text">
                        <i class="fas fa-filter"></i>
                    </span>
                    <select name="status" class="form-select">
                        <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Status</option>
                        <option value="owing" <?= $status_filter === 'owing' ? 'selected' : '' ?>>Owing</option>
                        <option value="paid" <?= $status_filter === 'paid' ? 'selected' : '' ?>>Paid</option>
                    </select>
                </div>
            </div>

            <!-- Date Filter Row -->
            <div class="col-12">
                <div class="date-filter-wrapper d-flex gap-2 align-items-center flex-wrap">
                    <div class="quick-filters btn-group">
                        <button type="button" class="btn btn-outline-primary active" onclick="setDateRange(0)">
                            Today
                        </button>
                        <button type="button" class="btn btn-outline-primary" onclick="setDateRange(7)">
                            Last 7 Days
                        </button>
                        <button type="button" class="btn btn-outline-primary" onclick="setDateRange(30)">
                            Last 30 Days
                        </button>
                        <button type="button" class="btn btn-outline-primary" onclick="setAllTime()">
                            All Time
                        </button>
                    </div>
                    <div class="custom-date-range d-flex gap-2 align-items-center ms-auto">
                        <div class="input-group">
                            <span class="input-group-text">From</span>
                            <input type="date" name="start_date" class="form-control" 
                                   value="<?= htmlspecialchars($start_date) ?>">
                        </div>
                        <div class="input-group">
                            <span class="input-group-text">To</span>
                            <input type="date" name="end_date" class="form-control" 
                                   value="<?= htmlspecialchars($end_date) ?>">
                        </div>
                        <button type="submit" class="btn btn-primary">
                            Apply Filters
                        </button>
                        <a href="owing_management.php" class="btn btn-outline-secondary">
                            Reset
                        </a>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- Toggle Buttons -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div class="btn-group">
            <button id="toggleOwedToMe" class="btn btn-toggle active">
                <i class="fas fa-arrow-right me-2"></i>Owed to Me
            </button>
            <button id="toggleIOwe" class="btn btn-toggle">
                <i class="fas fa-arrow-left me-2"></i>I Owe
            </button>
        </div>
    </div>

            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Phone Number</th>
                            <th>Amount</th>
                            <th>Type</th>
                            <th>Description</th>
                            <th>Paid</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="owingTableBody">
    <?php if (empty($owings)): ?>
        <tr>
            <td colspan="8" class="text-center py-4">
                <i class="fas fa-info-circle mb-2"></i>
                <p>No owings found for the selected date range.</p>
            </td>
        </tr>
    <?php else: ?>
        <?php foreach ($owings as $owing):
            $combined = $owing['amount'] + $owing['amount_paid']; 
        ?>
            <tr data-owing-type="<?= $owing['owing_type'] ?>" 
                data-amount="<?= $owing['amount'] ?>" 
                data-status="<?= $owing['status'] ?>">
                <td><?= htmlspecialchars($owing['person_name']) ?></td>
                <td><?= htmlspecialchars($owing['phone_number']) ?></td>
                <td><?= number_format($combined, 2) ?></td>
                <td><?= $owing['owing_type'] === 'owed_to' ? 'Owed to Me' : 'I Owe' ?></td>
                <td><?= htmlspecialchars($owing['description']) ?></td>
                <td><?= number_format($owing['amount_paid'], 2) ?></td>
                <td>
                    <span class="badge <?= $owing['status'] === 'Owing' ? 'badge-owing' : 'badge-paid' ?>">
                        <?= htmlspecialchars($owing['status']) ?>
                    </span>
                </td>
                <td>
                    <a href="view_payments.php?owing_id=<?= $owing['id'] ?>" 
                       class="btn btn-info btn-sm">View Payments</a>
                    <?php if ($owing['status'] === 'Owing'): ?>
                        <button class="btn btn-warning btn-sm" 
                                data-bs-toggle="modal" 
                                data-bs-target="#partialPaymentModal" 
                                data-owing-id="<?= $owing['id'] ?>" 
                                data-amount="<?= $owing['amount'] ?>">
                            Make Payment
                        </button>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
    <?php endif; ?>
</tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Partial Payment Modal -->
<div class="modal fade" id="partialPaymentModal" tabindex="-1" aria-labelledby="partialPaymentModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="add_partial_payment.php" method="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="partialPaymentModalLabel">Pay Small Small</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="owing_id" id="owing_id">
                    <div class="mb-3">
                        <label for="payment_amount" class="form-label">Amount to Pay</label>
                        <input type="number" class="form-control" id="payment_amount" name="payment_amount" required>
                    </div>
                    <div class="mb-3">
                        <label for="payment_date" class="form-label">Payment Date</label>
                        <input type="date" class="form-control" id="payment_date" name="payment_date" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Make Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>


<!-- Add Owing Modal -->
<div class="modal fade" id="addOwingModal" tabindex="-1" aria-labelledby="addOwingModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="add_owing.php" method="POST" id="addOwingForm">
                <div class="modal-header">
                    <h5 class="modal-title" id="addOwingModalLabel">Add New Owing</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="person_name" class="form-label">Name</label>
                        <input type="text" class="form-control" id="person_name" name="person_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="phone_number" class="form-label">Phone Number</label>
                        <input type="text" class="form-control" id="phone_number" name="phone_number" required>
                    </div>
                    <div class="mb-3">
                        <label for="amount" class="form-label">Amount</label>
                        <input type="number" class="form-control" id="amount" name="amount" required>
                    </div>
                    <div class="mb-3">
                        <label for="owing_type" class="form-label">Owing Type</label>
                        <select class="form-select" id="owing_type" name="owing_type" required>
                            <option value="owed_to">Owed to Me</option>
                            <option value="owed_by">I Owe</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="due_date" class="form-label">Due Date</label>
                        <input type="date" class="form-control" id="due_date" name="due_date" required>
                    </div>
                    <div class="mb-3">
                        <select style="visibility: hidden;" class="form-select" id="status" name="status" required>
                            <option value="Owing">Owing</option>
                            <option value="Paid">Paid</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Save Owing</button>
                </div>
            </form>
        </div>
    </div>
</div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    
    <script>
    const owingTableBody = document.getElementById('owingTableBody');
    const totalOwedToMe = document.getElementById('totalOwedToMe');
    const totalIOwe = document.getElementById('totalIOwe');

    function updateTotals() {
    let owedToMe = 0;
    let iOwe = 0;

    // Reference the table body
    const owingTableBody = document.getElementById('owingTableBody');

    // Iterate through each row in the table body
    for (const row of owingTableBody.rows) {
        const status = row.dataset.status; // Get the 'data-status' attribute

        if (status.toLowerCase() !== 'owing') {
            continue; // Skip rows where status is not 'owing'
        }

        const amount = parseFloat(row.dataset.amount) || 0; // Get the amount and handle invalid numbers
        const owingType = row.dataset.owingType; // Get the 'data-owing-type' attribute

        // Calculate totals based on owing type
        if (owingType === 'owed_to') {
            owedToMe += amount;
        } else {
            iOwe += amount;
        }
    }

    // Update totals in the DOM
    const totalOwedToMe = document.getElementById('totalOwedToMe');
    const totalIOwe = document.getElementById('totalIOwe');

    totalOwedToMe.textContent = owedToMe.toFixed(2);
    totalIOwe.textContent = iOwe.toFixed(2);
}



    // Update totals on page load
    updateTotals();

    // Toggle buttons
    const toggleButtons = document.querySelectorAll('.btn-toggle');
    toggleButtons.forEach(button => {
        button.addEventListener('click', () => {
            const isActive = button.classList.contains('active');
            toggleButtons.forEach(btn => btn.classList.remove('active'));

            if (!isActive) {
                button.classList.add('active');
                const showingType = button.id === 'toggleOwedToMe' ? 'owed_to' : 'owed_by';
                for (const row of owingTableBody.rows) {
                    row.style.display = row.dataset.owingType === showingType ? '' : 'none';
                }
                updateTotals();
            } else {
                // Show all rows if the active button is clicked again
                for (const row of owingTableBody.rows) {
                    row.style.display = '';
                }
                updateTotals();
            }
        });
    });

    // JavaScript to set the owing ID and amount in the modal
const partialPaymentButtons = document.querySelectorAll('.btn-warning');
partialPaymentButtons.forEach(button => {
    button.addEventListener('click', () => {
        const owingId = button.getAttribute('data-owing-id');
        const amount = button.getAttribute('data-amount');
        document.getElementById('owing_id').value = owingId;
        document.getElementById('payment_amount').max = amount; // Set the max payment to the owing amount
    });
});


    a = 0;
    function toggleSidebar(x) {
       if(a  == 0){
        document.querySelector('.sidebar').classList.toggle('active');
        document.querySelector('.content').classList.toggle('active');
        x.innerHTML = '<i class="fa-solid fa-xmark"></i>'
        x.style.background='red'
        
        a = 1
    }else{
        document.querySelector('.sidebar').classList.toggle('active');
        document.querySelector('.content').classList.toggle('active');
        x.innerHTML = '<i class="fas fa-bars"></i>'
        x.style.background='blue'
        a = 0
       }
    }
   


</script>
<script>
    document.getElementById('statusFilter').addEventListener('change', function () {
        const selectedStatus = this.value.toLowerCase();
        const tableRows = document.querySelectorAll('#owingTableBody tr');

        tableRows.forEach(row => {
            const rowStatus = row.dataset.status.toLowerCase();
            if (selectedStatus === 'all' || rowStatus === selectedStatus) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    });
</script>
<script>
function setDateRange(days) {
    const form = document.getElementById('dateFilterForm');
    const startDate = form.querySelector('input[name="start_date"]');
    const endDate = form.querySelector('input[name="end_date"]');
    
    const end = new Date();
    const start = new Date();
    
    if (days > 0) {
        start.setDate(start.getDate() - days);
    }
    
    startDate.value = start.toISOString().split('T')[0];
    endDate.value = end.toISOString().split('T')[0];
    
    // Preserve other filters
    preserveFilters();
    form.submit();
}

function setAllTime() {
    const form = document.getElementById('dateFilterForm');
    // Add hidden input for all_time filter
    const allTimeInput = document.createElement('input');
    allTimeInput.type = 'hidden';
    allTimeInput.name = 'filter';
    allTimeInput.value = 'all_time';
    form.appendChild(allTimeInput);
    
    // Preserve other filters
    preserveFilters();
    form.submit();
}

function preserveFilters() {
    const form = document.getElementById('dateFilterForm');
    const status = form.querySelector('select[name="status"]').value;
    const username = form.querySelector('input[name="username"]').value;
    
    // Keep the current status and username filters
    if (status && status !== 'all') {
        const statusInput = document.createElement('input');
        statusInput.type = 'hidden';
        statusInput.name = 'status';
        statusInput.value = status;
        form.appendChild(statusInput);
    }
    
    if (username) {
        const usernameInput = document.createElement('input');
        usernameInput.type = 'hidden';
        usernameInput.name = 'username';
        usernameInput.value = username;
        form.appendChild(usernameInput);
    }
}
</script>
<script>
function setDateRange(days) {
    const form = document.getElementById('dateFilterForm');
    const startDate = form.querySelector('input[name="start_date"]');
    const endDate = form.querySelector('input[name="end_date"]');
    
    const end = new Date();
    const start = new Date();
    
    if (days > 0) {
        start.setDate(start.getDate() - days);
    }
    
    startDate.value = start.toISOString().split('T')[0];
    endDate.value = end.toISOString().split('T')[0];
    
    form.submit();
}

// Initialize date inputs with current values
document.addEventListener('DOMContentLoaded', function() {
    const startDate = document.querySelector('input[name="start_date"]');
    const endDate = document.querySelector('input[name="end_date"]');
    
    if (!startDate.value) {
        startDate.value = new Date().toISOString().split('T')[0];
    }
    if (!endDate.value) {
        endDate.value = new Date().toISOString().split('T')[0];
    }
});
</script>

</body>
</html>
