<?php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

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

$user = $_SESSION['user'];
$user_id = $user['id'] ?? 1;
$shop_id = $user['shop_id'] ?? null;
$user_role = $user['role'] ?? 'cashier';

// Check for success message
$success_message = '';
if (isset($_GET['added']) && $_GET['added'] == 1) {
    $success_message = '<div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle"></i> Purchase added successfully!
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>';
}

// Check for deleted message
if (isset($_GET['deleted']) && $_GET['deleted'] == 1) {
    $success_message = '<div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-trash-alt"></i> Purchase deleted successfully!
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>';
}

// Filter parameters
$filter_supplier = isset($_GET['supplier']) ? intval($_GET['supplier']) : 0;
$filter_date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$filter_date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$filter_invoice = isset($_GET['invoice']) ? trim($_GET['invoice']) : '';

// Build WHERE clause
$where_conditions = [];
$params = [];

// Always filter by shop
if ($shop_id > 0 && $user_role != 'admin') {
    $where_conditions[] = "p.shop_id = ?";
    $params[] = $shop_id;
} elseif ($user_role == 'admin' && $shop_id > 0) {
    $where_conditions[] = "p.shop_id = ?";
    $params[] = $shop_id;
}

// Apply filters
if ($filter_supplier > 0) {
    $where_conditions[] = "p.supplier_id = ?";
    $params[] = $filter_supplier;
}

if (!empty($filter_date_from)) {
    $where_conditions[] = "p.purchase_date >= ?";
    $params[] = $filter_date_from;
}

if (!empty($filter_date_to)) {
    $where_conditions[] = "p.purchase_date <= ?";
    $params[] = $filter_date_to;
}

if (!empty($filter_invoice)) {
    $where_conditions[] = "p.invoice_no LIKE ?";
    $params[] = "%$filter_invoice%";
}

// Build final WHERE clause
$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = "WHERE " . implode(" AND ", $where_conditions);
}

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total FROM purchases p $where_clause";
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($params);
$total_purchases = $count_stmt->fetch(PDO::FETCH_ASSOC)['total'];

// Pagination
$per_page = 20;
$total_pages = ceil($total_purchases / $per_page);
$current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($current_page - 1) * $per_page;

// Get purchases with pagination
$sql = "SELECT p.*, 
               s.name as supplier_name,
               u.fullname as created_by_name,
               sh.name as shop_name,
               COUNT(pl.id) as item_count,
               SUM(pl.qty) as total_qty
        FROM purchases p 
        LEFT JOIN suppliers s ON p.supplier_id = s.id
        LEFT JOIN users u ON p.created_by = u.id
        LEFT JOIN shops sh ON p.shop_id = sh.id
        LEFT JOIN purchase_lines pl ON p.id = pl.purchase_id
        $where_clause
        GROUP BY p.id
        ORDER BY p.purchase_date DESC, p.id DESC
        LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get suppliers for filter dropdown
$suppliers = $pdo->query("SELECT id, name FROM suppliers ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// Get shops for admin filter
$shops = [];
if ($user_role == 'admin') {
    $shops = $pdo->query("SELECT id, name FROM shops WHERE is_active = 1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
}
?>

<style>
    .table-hover tbody tr:hover {
        background-color: #f5f5f5;
    }
    
    .badge-pill {
        padding: 5px 10px;
        font-size: 12px;
    }
    
    .purchase-type-direct {
        border-left: 4px solid #28a745;
    }
    
    .purchase-type-invoice {
        border-left: 4px solid #007bff;
    }
    
    .filter-card {
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 5px;
        padding: 15px;
        margin-bottom: 20px;
    }
    
    .action-buttons .btn {
        padding: 3px 8px;
        font-size: 12px;
        margin-right: 3px;
    }
    
    .pagination {
        margin-bottom: 0;
    }
    
    @media (max-width: 768px) {
        .table-responsive {
            font-size: 14px;
        }
        
        .action-buttons {
            display: flex;
            flex-wrap: wrap;
        }
        
        .action-buttons .btn {
            margin-bottom: 3px;
        }
    }
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="text-primary">
                <i class="fas fa-shopping-cart"></i> All Purchases
            </h3>
            <p class="text-muted mb-0">View and manage all purchase records</p>
        </div>
        <div>
            <a href="add_purchase.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> New Purchase
            </a>
            <a href="add_batch.php" class="btn btn-success ml-2">
                <i class="fas fa-box"></i> Add Single Batch
            </a>
        </div>
    </div>

    <?= $success_message ?>

    <!-- Filter Card -->
    <div class="card filter-card">
        <div class="card-body">
            <h5 class="card-title"><i class="fas fa-filter"></i> Filter Purchases</h5>
            <form method="GET" action="" class="row">
                <?php if ($user_role == 'admin' && !empty($shops)): ?>
                <div class="col-md-3 mb-3">
                    <label>Shop</label>
                    <select name="shop_id" class="form-control">
                        <option value="">All Shops</option>
                        <?php foreach ($shops as $shop): ?>
                            <option value="<?= $shop['id'] ?>" <?= ($shop_id == $shop['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($shop['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                
                <div class="col-md-3 mb-3">
                    <label>Supplier</label>
                    <select name="supplier" class="form-control">
                        <option value="">All Suppliers</option>
                        <?php foreach ($suppliers as $supplier): ?>
                            <option value="<?= $supplier['id'] ?>" <?= ($filter_supplier == $supplier['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($supplier['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2 mb-3">
                    <label>Date From</label>
                    <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($filter_date_from) ?>">
                </div>
                
                <div class="col-md-2 mb-3">
                    <label>Date To</label>
                    <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($filter_date_to) ?>">
                </div>
                
                <div class="col-md-2 mb-3">
                    <label>Invoice No</label>
                    <input type="text" name="invoice" class="form-control" placeholder="Search..." value="<?= htmlspecialchars($filter_invoice) ?>">
                </div>
                
                <div class="col-md-2 mb-3 d-flex align-items-end">
                    <div class="btn-group w-100">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i> Filter
                        </button>
                        <a href="list_purchases.php" class="btn btn-outline-secondary">
                            <i class="fas fa-redo"></i> Clear
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card text-white bg-primary">
                <div class="card-body">
                    <h6 class="card-title">Total Purchases</h6>
                    <h4><?= number_format($total_purchases) ?></h4>
                    <p class="card-text small">All time records</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-white bg-success">
                <div class="card-body">
                    <h6 class="card-title">This Month</h6>
                    <h4>
                        <?php 
                        $month_sql = "SELECT COUNT(*) FROM purchases WHERE MONTH(purchase_date) = MONTH(CURDATE()) AND YEAR(purchase_date) = YEAR(CURDATE())";
                        if ($shop_id > 0) {
                            $month_sql .= " AND shop_id = $shop_id";
                        }
                        $month_count = $pdo->query($month_sql)->fetchColumn();
                        echo number_format($month_count);
                        ?>
                    </h4>
                    <p class="card-text small">Current month</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-white bg-info">
                <div class="card-body">
                    <h6 class="card-title">This Week</h6>
                    <h4>
                        <?php 
                        $week_sql = "SELECT COUNT(*) FROM purchases WHERE YEARWEEK(purchase_date, 1) = YEARWEEK(CURDATE(), 1)";
                        if ($shop_id > 0) {
                            $week_sql .= " AND shop_id = $shop_id";
                        }
                        $week_count = $pdo->query($week_sql)->fetchColumn();
                        echo number_format($week_count);
                        ?>
                    </h4>
                    <p class="card-text small">Current week</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-white bg-warning">
                <div class="card-body">
                    <h6 class="card-title">Today</h6>
                    <h4>
                        <?php 
                        $today_sql = "SELECT COUNT(*) FROM purchases WHERE DATE(purchase_date) = CURDATE()";
                        if ($shop_id > 0) {
                            $today_sql .= " AND shop_id = $shop_id";
                        }
                        $today_count = $pdo->query($today_sql)->fetchColumn();
                        echo number_format($today_count);
                        ?>
                    </h4>
                    <p class="card-text small">Today's purchases</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Purchases Table -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
                <i class="fas fa-list"></i> Purchase Records 
                <span class="badge badge-secondary"><?= number_format($total_purchases) ?></span>
            </h5>
            <div>
                <span class="text-muted small">
                    Page <?= $current_page ?> of <?= $total_pages ?>
                </span>
            </div>
        </div>
        <div class="card-body">
            <?php if (empty($purchases)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">No purchases found</h5>
                    <p class="text-muted">Try adjusting your filters or add a new purchase.</p>
                    <a href="add_purchase.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add Your First Purchase
                    </a>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover table-bordered">
                        <thead class="thead-light">
                            <tr>
                                <th>Invoice #</th>
                                <th>Date</th>
                                <th>Supplier</th>
                                <th class="text-center">Items</th>
                                <th class="text-center">Quantity</th>
                                <th class="text-right">Amount</th>
                                <th>Created By</th>
                                <th>Shop</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($purchases as $purchase): 
                                $is_direct = strpos($purchase['invoice_no'], 'DIRECT') === 0;
                                $row_class = $is_direct ? 'purchase-type-direct' : 'purchase-type-invoice';
                            ?>
                            <tr class="<?= $row_class ?>">
                                <td>
                                    <strong><?= htmlspecialchars($purchase['invoice_no']) ?></strong>
                                    <?php if ($is_direct): ?>
                                        <span class="badge badge-success badge-pill ml-1" title="Direct Batch Addition">Batch</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= date('d-M-Y', strtotime($purchase['purchase_date'])) ?></td>
                                <td>
                                    <?php if ($purchase['supplier_name']): ?>
                                        <?= htmlspecialchars($purchase['supplier_name']) ?>
                                    <?php else: ?>
                                        <span class="text-muted">Direct</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <span class="badge badge-info"><?= $purchase['item_count'] ?></span>
                                </td>
                                <td class="text-center">
                                    <span class="badge badge-secondary"><?= $purchase['total_qty'] ?? 0 ?></span>
                                </td>
                                <td class="text-right">
                                    <strong>TSh <?= number_format($purchase['total'], 2) ?></strong>
                                </td>
                                <td><?= htmlspecialchars($purchase['created_by_name'] ?? 'System') ?></td>
                                <td><?= htmlspecialchars($purchase['shop_name'] ?? 'N/A') ?></td>
                                <td class="action-buttons">
                                 <?php if($_SESSION['user']['role']!='admin')
								{ 
								echo""; // display none for non-admins
								}
								else
								{?>
                                    <a href="purchase_view.php?id=<?= $purchase['id'] ?>" class="btn btn-sm btn-info" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="print_purchase.php?id=<?= $purchase['id'] ?>" target="_blank" class="btn btn-sm btn-secondary" title="Print Receipt">
                                        <i class="fas fa-print"></i>
                                    </a>
                                    <?php if ($user_role == 'admin' || $user_id == $purchase['created_by']): ?>
                                        <a href="edit_purchase.php?id=<?= $purchase['id'] ?>" class="btn btn-sm btn-warning" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <button type="button" class="btn btn-sm btn-danger delete-purchase" 
                                                data-id="<?= $purchase['id'] ?>" 
                                                data-invoice="<?= htmlspecialchars($purchase['invoice_no']) ?>"
                                                title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    <?php endif; ?><br>
								<?php } ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center">
                        <li class="page-item <?= $current_page <= 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=<?= $current_page - 1 ?><?= !empty($_GET) ? '&' . http_build_query($_GET) : '' ?>">
                                <i class="fas fa-chevron-left"></i>
                            </a>
                        </li>
                        
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <?php if ($i == 1 || $i == $total_pages || ($i >= $current_page - 2 && $i <= $current_page + 2)): ?>
                                <li class="page-item <?= $i == $current_page ? 'active' : '' ?>">
                                    <a class="page-link" href="?page=<?= $i ?><?= !empty($_GET) ? '&' . http_build_query($_GET) : '' ?>">
                                        <?= $i ?>
                                    </a>
                                </li>
                            <?php elseif ($i == $current_page - 3 || $i == $current_page + 3): ?>
                                <li class="page-item disabled">
                                    <span class="page-link">...</span>
                                </li>
                            <?php endif; ?>
                        <?php endfor; ?>
                        
                        <li class="page-item <?= $current_page >= $total_pages ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=<?= $current_page + 1 ?><?= !empty($_GET) ? '&' . http_build_query($_GET) : '' ?>">
                                <i class="fas fa-chevron-right"></i>
                            </a>
                        </li>
                    </ul>
                </nav>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteModalLabel">
                    <i class="fas fa-exclamation-triangle"></i> Confirm Delete
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete purchase <strong id="deleteInvoiceNo"></strong>?</p>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-circle"></i> <strong>Warning:</strong> This action cannot be undone. 
                    Deleting a purchase will also remove all associated purchase lines and inventory movements.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <a href="#" id="confirmDelete" class="btn btn-danger">
                    <i class="fas fa-trash"></i> Delete Purchase
                </a>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Delete purchase confirmation
    $('.delete-purchase').on('click', function(e) {
        e.preventDefault();
        
        var purchaseId = $(this).data('id');
        var invoiceNo = $(this).data('invoice');
        
        $('#deleteInvoiceNo').text(invoiceNo);
        $('#confirmDelete').attr('href', 'delete_purchase.php?id=' + purchaseId);
        $('#deleteModal').modal('show');
    });
    
    // Auto-dismiss alerts after 5 seconds
    setTimeout(function() {
        $('.alert').fadeOut('slow');
    }, 5000);
    
    // Export functionality (optional)
    $('#exportBtn').on('click', function() {
        // You can implement CSV/Excel export here
        alert('Export functionality would be implemented here');
    });
});
</script>

<?php require_once '../includes/footer.php'; ?>