<?php
session_start();
require_once 'includes/auth.php';
requireLogin();
require_once 'config/database.php';
require_once 'includes/functions.php';

$userId = $_SESSION['user_id'];

$stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();

if (!$company) {
    header('Location: settings.php');
    exit;
}

$companyId = $company['id'];

// Handle delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $deleteId = $_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM documents WHERE id = ? AND company_id = ?");
    $stmt->execute([$deleteId, $companyId]);
    header('Location: documents.php?msg=deleted');
    exit;
}

$type_filter = $_GET['type'] ?? 'all';
$sql = "SELECT d.*, c.name as client_name FROM documents d LEFT JOIN clients c ON d.client_id = c.id WHERE d.company_id = ?";
$params = [$companyId];

if ($type_filter != 'all') {
    $sql .= " AND d.type = ?";
    $params[] = $type_filter;
}
$sql .= " ORDER BY d.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$documents = $stmt->fetchAll();

include 'includes/header.php';
?>

<?php if (isset($_GET['msg'])): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4">
        <?php if ($_GET['msg'] == 'deleted') echo 'Document deleted successfully!'; ?>
        <?php if ($_GET['msg'] == 'saved') echo 'Document saved successfully!'; ?>
    </div>
<?php endif; ?>

<?php if (isset($_SESSION['success'])): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
<?php endif; ?>

<?php if (isset($_SESSION['error'])): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-4"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></div>
<?php endif; ?>

<div class="mb-4 flex justify-between items-center flex-wrap gap-2">
    <div class="flex space-x-2 flex-wrap">
        <a href="?type=all" class="px-4 py-2 rounded-lg <?php echo $type_filter == 'all' ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'; ?>">All</a>
        <a href="?type=invoice" class="px-4 py-2 rounded-lg <?php echo $type_filter == 'invoice' ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'; ?>">Invoices</a>
        <a href="?type=estimate" class="px-4 py-2 rounded-lg <?php echo $type_filter == 'estimate' ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'; ?>">Estimates</a>
        <a href="?type=quotation" class="px-4 py-2 rounded-lg <?php echo $type_filter == 'quotation' ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'; ?>">Quotations</a>
        <a href="?type=receipt" class="px-4 py-2 rounded-lg <?php echo $type_filter == 'receipt' ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'; ?>">Receipts</a>
        <a href="?type=proforma" class="px-4 py-2 rounded-lg <?php echo $type_filter == 'proforma' ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'; ?>">Proforma</a>
    </div>
    <a href="document-form.php" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition"><i class="fas fa-plus mr-2"></i>New Document</a>
</div>

<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full">
            <thead class="bg-gray-50 dark:bg-gray-700/50">
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Number</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Type</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Client</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Issue Date</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Amount</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Status</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                <?php if (empty($documents)): ?>
                    <tr>
                        <td colspan="7" class="px-6 py-12 text-center text-gray-500 dark:text-gray-400">No documents found. Click "New Document" to create one.</td>
                    </tr>
                <?php else: foreach ($documents as $doc): ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                        <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white"><?php echo htmlspecialchars($doc['document_number']); ?></td>
                        <td class="px-6 py-4 text-sm capitalize"><span class="px-2 py-1 text-xs rounded-full bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200"><?php echo $doc['type']; ?></span></td>
                        <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400"><?php echo htmlspecialchars($doc['client_name'] ?? 'N/A'); ?></td>
                        <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400"><?php echo date('M d, Y', strtotime($doc['issue_date'])); ?></td>
                        <td class="px-6 py-4 text-sm font-semibold text-gray-700 dark:text-gray-300"><?php echo formatMoney($doc['total'], $doc['currency']); ?></td>
                        <td class="px-6 py-4">
                            <form method="POST" action="document-status.php" class="inline-block">
                                <input type="hidden" name="id" value="<?php echo $doc['id']; ?>">
                                <input type="hidden" name="return_url" value="documents.php">
                                <select name="status" onchange="this.form.submit()" class="text-xs border rounded px-1 py-0.5 dark:bg-gray-700 dark:border-gray-600">
                                    <option value="draft" <?php echo $doc['status'] == 'draft' ? 'selected' : ''; ?>>Draft</option>
                                    <option value="sent" <?php echo $doc['status'] == 'sent' ? 'selected' : ''; ?>>Sent</option>
                                    <?php if ($doc['type'] == 'invoice'): ?>
                                        <option value="paid" <?php echo $doc['status'] == 'paid' ? 'selected' : ''; ?>>Paid</option>
                                        <option value="partially_paid" <?php echo $doc['status'] == 'partially_paid' ? 'selected' : ''; ?>>Partially Paid</option>
                                        <option value="overdue" <?php echo $doc['status'] == 'overdue' ? 'selected' : ''; ?>>Overdue</option>
                                    <?php endif; ?>
                                    <?php if ($doc['type'] == 'estimate'): ?>
                                        <option value="accepted" <?php echo $doc['status'] == 'accepted' ? 'selected' : ''; ?>>Accepted</option>
                                        <option value="rejected" <?php echo $doc['status'] == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                    <?php endif; ?>
                                </select>
                            </form>
                        </td>
                        <td class="px-6 py-4 text-sm whitespace-nowrap">
                            <a href="document-view.php?id=<?php echo $doc['id']; ?>" class="text-blue-600 hover:text-blue-800 mr-2"><i class="fas fa-eye"></i></a>
                            <a href="document-form.php?id=<?php echo $doc['id']; ?>" class="text-green-600 hover:text-green-800 mr-2"><i class="fas fa-edit"></i></a>
                            <a href="document-pdf.php?id=<?php echo $doc['id']; ?>" target="_blank" class="text-purple-600 hover:text-purple-800 mr-2"><i class="fas fa-file-pdf"></i></a>
                            <a href="?delete=<?php echo $doc['id']; ?>" onclick="return confirm('Are you sure? This cannot be undone.')" class="text-red-600 hover:text-red-800"><i class="fas fa-trash"></i></a>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

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