<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

include('../config/db.php');

$username = $_SESSION['username'];

// Calculate total owings for the user
$owingStmt = $pdo->prepare("SELECT SUM(amount) AS total_owing FROM owings WHERE created_by = :username AND status = 'owing'");
$owingStmt->execute(['username' => $username]);
$owingRow = $owingStmt->fetch(PDO::FETCH_ASSOC);
$totalOwing = $owingRow['total_owing'] ?? 0;

// Fetch pharmacy name
$query = "SELECT pharmacy_name FROM settings LIMIT 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
$setting = $stmt->fetch(PDO::FETCH_ASSOC);
$pharmacy_name = $setting['pharmacy_name'] ?? 'Default Pharmacy Name';

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Owings - <?= htmlspecialchars($pharmacy_name) ?></title>
    <link rel="stylesheet" href="..\libs\bootsrtap2\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap2\js\bootstrap.bundle.min.js"></script>
    
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #34495e;
            --accent-color: #3498db;
            --success-color: #2ecc71;
            --warning-color: #f1c40f;
            --danger-color: #e74c3c;
            --light-color: #ecf0f1;
            --dark-color: #2c3e50;
            --border-color: #bdc3c7;
            --background-color: #f8f9fa;
            --shadow-sm: 0 2px 4px rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px rgba(0,0,0,0.1);
            --transition: all 0.3s ease;
        }

        body {
            margin: 0;
            padding: 0;
            background-color: var(--background-color);
            font-family: Arial, sans-serif;
            min-height: 100vh;
        }

        .wrapper {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            min-height: 100vh;
            background: var(--primary-color);
            position: fixed;
            left: 0;
            top: 0;
            z-index: 1000;
        }

        .sidebar-header {
            padding: 20px;
            background: var(--secondary-color);
            text-align: center;
        }

        .sidebar-header h2 {
            color: var(--accent-color);
            margin: 0;
            font-size: 1.25rem;
        }

        .menu-section {
            padding: 15px 0;
        }

        .menu-section a {
            padding: 12px 20px;
            color: var(--light-color);
            text-decoration: none;
            display: flex;
            align-items: center;
            transition: 0.3s;
        }

        .menu-section a i {
            margin-right: 10px;
            width: 20px;
        }

        .menu-section a:hover,
        .menu-section a.active {
            background: var(--secondary-color);
            border-left: 4px solid var(--accent-color);
        }

        .content {
            flex: 1;
            margin-left: 250px;
            padding: 20px;
            transition: margin-left 0.3s ease;
        }

        .top-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            background: white;
            padding: 1.25rem;
            border-radius: 10px;
            box-shadow: var(--shadow-sm);
        }

        .page-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--dark-color);
            margin: 0;
        }

        .btn-add-owing {
            padding: 0.625rem 1.25rem;
            font-weight: 500;
            transition: var(--transition);
        }

        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .summary-card {
            background: white;
            padding: 1.5rem;
            border-radius: 10px;
            box-shadow: var(--shadow-md);
            position: relative;
            overflow: hidden;
            transition: var(--transition);
        }

        .summary-card:hover {
            transform: translateY(-3px);
        }

        .summary-card h4 {
            display: flex;
            align-items: center;
            gap: 10px;
            color: var(--text-muted);
            font-size: 0.9rem;
            margin-bottom: 10px;
        }

        .summary-card .amount {
            font-size: 1.8rem;
            font-weight: bold;
            color: var(--primary-color);
        }

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

        .table-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: var(--shadow-md);
            margin-top: 2rem;
        }

        .table > :not(caption) > * > * {
            padding: 1rem 1.5rem;
        }

        .table thead th {
            background: var(--light-color);
            padding: 1rem;
            font-weight: 600;
        }

        .table tbody td {
            padding: 1rem;
            vertical-align: middle;
        }

        .badge {
            padding: 0.5rem 1rem;
            border-radius: 50px;
            font-weight: 500;
        }

        .badge-owing {
            background: var(--danger-color);
            color: white;
        }

        .badge-paid {
            background: var(--success-color);
            color: white;
        }

        .btn-primary {
            background: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-primary:hover {
            background: var(--secondary-color);
            border-color: var(--secondary-color);
        }

        .modal-content {
            border-radius: 10px;
            box-shadow: var(--shadow-md);
        }

        .modal-header {
            background: var(--primary-color);
            color: white;
            border-radius: 10px 10px 0 0;
        }

        .modal-title {
            font-weight: 600;
        }

        .btn-close {
            filter: brightness(0) invert(1);
        }

        .form-label {
            font-weight: 500;
            color: var(--dark-color);
        }

        .form-control, .form-select {
            border-radius: 8px;
            padding: 0.625rem;
            border-color: var(--border-color);
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--accent-color);
            box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
        }

        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            .sidebar.active {
                transform: translateX(0);
            }
            .content {
                margin-left: 0;
            }
            .content.active {
                margin-left: 250px;
            }
            .summary-cards {
                grid-template-columns: 1fr;
            }
        }

        .toggle-nav {
            display: none; /* Hide by default */
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 0.5rem;
            border-radius: 4px;
            cursor: pointer;
            transition: var(--transition);
        }

        /* Only show on mobile */
        @media (max-width: 768px) {
            .toggle-nav {
                display: block;
            }
        }

        .btn-group .btn {
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .btn-group .btn.active {
            background-color: var(--primary-color);
            color: white;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header">
            <h2><?= htmlspecialchars($pharmacy_name) ?></h2>
        </div>
        <div class="menu-section">
            <a href="staff_dashboard.php">
                <i class="fas fa-home"></i>
                <span>Dashboard</span>
            </a>
            <a href="sell_drug.php">
                <i class="fas fa-cash-register"></i>
                <span>Point of Sale</span>
            </a>
            <a href="owing_management.php" class="active">
                <i class="fas fa-money-bill-wave"></i>
                <span>Owing Management</span>
            </a>
            <a href="staff_sales.php">
                <i class="fas fa-chart-line"></i>
                <span>Sales History</span>
            </a>
        </div>
        <div class="sidebar-footer">
            <a href="logout.php">
                <i class="fas fa-sign-out-alt"></i>
                <span>Logout</span>
            </a>
        </div>
    </div>

    <div class="content">
        <div class="top-bar">
            <div class="d-flex align-items-center">
                <button class="toggle-nav me-3" onclick="toggleSidebar(this)">
                    <i class="fas fa-bars"></i>
                </button>
                <h4 class="page-title">Owing Management</h4>
            </div>
            <button type="button" class="btn btn-primary btn-add-owing" data-bs-toggle="modal" data-bs-target="#addOwingModal">
                <i class="fas fa-plus me-2"></i>Add New Owing
            </button>
        </div>

        <div class="summary-cards">
            <div class="summary-card">
                <h4><i class="fas fa-arrow-right"></i> Owed to Me</h4>
                <div class="amount">₦<span id="totalOwedToMe">0.00</div>
            </div>
            <div class="summary-card">
                <h4><i class="fas fa-arrow-left"></i> I Owe</h4>
                <div class="amount">₦<span id="totalIOwe">0.00</div>
            </div>
        </div>

        <div class="filter-section">
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="btn-group w-100">
                        <button id="toggleOwedToMe" class="btn btn-outline-primary active">Owed to Me</button>
                        <button id="toggleIOwe" class="btn btn-outline-primary">Owed By</button>
                    </div>
                </div>
                <div class="col-md-4">
                    <select id="statusFilter" class="form-select">
                        <option value="all">All Status</option>
                        <option value="Owing">Owing</option>
                        <option value="Paid">Paid</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <input type="text" class="form-control" id="searchInput" 
                           placeholder="Search by name or phone...">
                </div>
            </div>
        </div>

        <div class="table-section">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Name</th>
                            <th>Phone Number</th>
                            <th>Amount</th>
                            <th>Type</th>
                            <th>Description</th>
                            <th>Amount Paid</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="owingTableBody">
                        <?php
require '../config/db.php';

// Check if the user is logged in
if (!isset($_SESSION['username'])) {
    // Redirect to login page if not logged in
    header("Location: login.php");
    exit();
}

$username = $_SESSION['username']; // Assuming the user's ID is stored in the session

// Query to fetch only owings created by the logged-in user
$sql = "SELECT * FROM owings WHERE created_by = :username ORDER BY id DESC";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username);
$stmt->execute();
$owings = $stmt->fetchAll();

$total_combined = 0;
foreach ($owings as $owing):
    $combined = $owing['amount'] + $owing['amount_paid']; 
    $total_combined += $combined;
?>
<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>
    </td>
</tr>
<?php endforeach; ?>

                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add Owing Modal -->
<div class="modal fade" id="addOwingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Owing</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addOwingForm" method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="personName" class="form-label">Person Name</label>
                        <input type="text" class="form-control" id="personName" name="person_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="phoneNumber" class="form-label">Phone Number</label>
                        <input type="text" class="form-control" id="phoneNumber" 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" min="0" step="0.01" required>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="owingType" class="form-label">Owing Type</label>
                        <select class="form-select" id="owingType" name="owing_type" required>
                            <option value="owed_to">Owed to Me</option>
                            <option value="owed_by">I Owe</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Owing</button>
                </div>
            </form>
        </div>
    </div>
</div>

    <script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Bootstrap modal
    const addOwingModal = new bootstrap.Modal(document.getElementById('addOwingModal'));

    // Filter functionality
    function applyFilters() {
        const searchText = document.getElementById('searchInput').value.toLowerCase();
        const selectedStatus = document.getElementById('statusFilter').value.toLowerCase();
        const rows = document.querySelectorAll('#owingTableBody tr');

        rows.forEach(row => {
            const name = row.cells[0].textContent.toLowerCase();
            const phone = row.cells[1].textContent.toLowerCase();
            const rowStatus = row.dataset.status.toLowerCase();
            const owingType = row.dataset.owingType;

            const matchesSearch = name.includes(searchText) || phone.includes(searchText);
            const matchesStatus = selectedStatus === 'all' || rowStatus === selectedStatus;
            
            // Check active toggle button
            const activeToggle = document.querySelector('.btn-group .active');
            const matchesToggle = !activeToggle || 
                                (activeToggle.id === 'toggleOwedToMe' && owingType === 'owed_to') ||
                                (activeToggle.id === 'toggleIOwe' && owingType === 'owed_by');

            row.style.display = (matchesSearch && matchesStatus && matchesToggle) ? '' : 'none';
        });

        updateTotals();
    }

    // Add event listeners
    document.getElementById('searchInput').addEventListener('keyup', applyFilters);
    document.getElementById('statusFilter').addEventListener('change', applyFilters);

    // Toggle buttons
    const toggleOwedToMe = document.getElementById('toggleOwedToMe');
    const toggleIOwe = document.getElementById('toggleIOwe');
    
    [toggleOwedToMe, toggleIOwe].forEach(button => {
        button.addEventListener('click', function() {
            const wasActive = this.classList.contains('active');
            [toggleOwedToMe, toggleIOwe].forEach(btn => btn.classList.remove('active'));
            if (!wasActive) {
                this.classList.add('active');
            }
            applyFilters();
        });
    });

    // Form submission
    document.getElementById('addOwingForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Get form data
        const formData = new FormData();
        formData.append('person_name', this.person_name.value);
        formData.append('phone_number', this.phone_number.value);
        formData.append('amount', this.amount.value);
        formData.append('owing_type', this.owing_type.value);
        formData.append('description', this.description.value);
        formData.append('created_by', '<?= $_SESSION['username'] ?>');
        formData.append('due_date', new Date().toISOString().split('T')[0]); // Current date as due date
        
        const submitBtn = this.querySelector('[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...';
        
        // Use standard form submission
        fetch('add_owing.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(html => {
            // Check if response contains success message
            if (html.includes('Owing record saved successfully')) {
                // Close modal and reload page
                const modal = bootstrap.Modal.getInstance(document.getElementById('addOwingModal'));
                modal.hide();
                location.reload();
            } else {
                // Show error message
                alert('Failed to save owing record');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error saving owing record');
        })
        .finally(() => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Save Owing';
        });
    });

    // Function to update totals
    function updateTotals() {
        let owedToMe = 0;
        let iOwe = 0;
        
        const visibleRows = Array.from(document.querySelectorAll('#owingTableBody tr'))
            .filter(row => row.style.display !== 'none');
        
        visibleRows.forEach(row => {
            if (row.dataset.status.toLowerCase() === 'owing') {
                const amount = parseFloat(row.dataset.amount) || 0;
                if (row.dataset.owingType === 'owed_to') {
                    owedToMe += amount;
                } else if (row.dataset.owingType === 'owed_by') {
                    iOwe += amount;
                }
            }
        });

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

    // Initial totals update
    updateTotals();
});
</script>
</body>
</html>
