<?php
session_start();
require_once("../config/config.php");

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

$success = isset($_GET['success']) ? "Purchase Order created successfully!" : "";
$error = "";

// Handle Delete (Optional - be careful with business logic)
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $po_id = (int)$_GET['delete'];
    try {
        $conn->begin_transaction();
        
        // Delete items first
        $conn->query("DELETE FROM purchase_order_from_client_items WHERE purchase_order_from_client_id = $po_id");
        // Delete header
        $conn->query("DELETE FROM purchase_order_from_client WHERE id = $po_id");
        
        $conn->commit();
        header("Location: po_from_client_list.php?success=Purchase Order deleted successfully");
        exit();
    } catch (Exception $e) {
        $conn->rollback();
        $error = "Failed to delete Purchase Order.";
    }
}

// Fetch All Purchase Orders
$query = "
    SELECT 
        po.id,
        po.order_number,
        po.project_id,
        po.total_basic,
        po.total_gst,
        po.grand_total,
        po.created_at,
        p.project_code,
        p.project_name,
        u.full_name AS created_by_name,
        COUNT(poi.id) AS item_count
    FROM purchase_order_from_client po
    LEFT JOIN project_master p ON po.project_id = p.id
    LEFT JOIN users u ON po.created_by = u.id
    LEFT JOIN purchase_order_from_client_items poi ON po.id = poi.purchase_order_from_client_id
    GROUP BY po.id
    ORDER BY po.created_at DESC
";

$result = $conn->query($query);
$pos = $result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Purchase Orders from Client</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }
        .container { max-width: 1350px; margin: auto; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 25px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
        }
        .header h1 {
            font-size: clamp(28px, 5.5vw, 42px);
            font-weight: 700;
        }

        .top-bar {
            padding: 25px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            background: rgba(255,255,255,0.05);
        }

        .search-box {
            flex: 1;
            min-width: 280px;
        }
        .search-box input {
            width: 100%;
            padding: 14px 20px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 16px;
            color: white;
            font-size: 16px;
        }

        .add-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 14px 28px;
            border-radius: 16px;
            text-decoration: none;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 10px 25px rgba(168,85,247,0.4);
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }
        th {
            background: rgba(168,85,247,0.3);
            padding: 18px 16px;
            text-align: left;
            font-weight: 600;
        }
        td {
            padding: 18px 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .po-number {
            font-weight: 700;
            color: #c4b5fd;
        }

        .action-btns a {
            margin: 0 6px;
            padding: 8px 14px;
            border-radius: 10px;
            text-decoration: none;
            font-size: 0.95rem;
        }
        .btn-view  { background: rgba(59,130,246,0.2); color: #60a5fa; }
        .btn-edit  { background: rgba(234,179,8,0.2); color: #fde047; }
        .btn-delete{ background: rgba(239,68,68,0.2); color: #f87171; }

        .message {
            padding: 16px 24px;
            border-radius: 16px;
            margin: 20px 40px;
            font-weight: 600;
        }
        .success { background: rgba(34,197,94,0.25); border:1px solid #4ade80; color:#86efac; }

        .no-data {
            text-align: center;
            padding: 100px 20px;
            color: #94a3b8;
        }
        .no-data i { font-size: 4.5rem; margin-bottom: 20px; opacity: 0.5; }

        @media (max-width: 768px) {
            .top-bar { flex-direction: column; align-items: stretch; }
            th, td { padding: 14px 10px; font-size: 0.95rem; }
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">

        <div class="header">
            <h1><i class="fas fa-file-invoice-dollar"></i> Purchase Orders from Client</h1>
            <p style="margin-top:12px; opacity:0.9;">All client purchase orders</p>
        </div>

        <div class="top-bar">
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Search by Order No, Project or Client..." onkeyup="filterTable()">
            </div>
            <a href="add_po_from_client.php" class="add-btn">
                <i class="fas fa-plus"></i> New Purchase Order
            </a>
        </div>

        <?php if ($success): ?>
            <div class="message success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="message" style="background:rgba(239,68,68,0.25); color:#fca5a5;"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <div style="padding:0 40px 40px;">
            <?php if (empty($pos)): ?>
                <div class="no-data">
                    <i class="fas fa-file-invoice"></i>
                    <h2>No Purchase Orders Found</h2>
                    <p>Create your first Purchase Order from Client.</p>
                </div>
            <?php else: ?>
                <table id="poTable">
                    <thead>
                        <tr>
                            <th>Order Number</th>
                            <th>Project</th>
                            <th>Created By</th>
                            <th>Date</th>
                            <th>Items</th>
                            <th>Basic Total</th>
                            <th>Grand Total</th>
                            <th style="text-align:center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pos as $po): ?>
                        <tr>
                            <td class="po-number"><?= htmlspecialchars($po['order_number']) ?></td>
                            <td>
                                <?= htmlspecialchars($po['project_code'] ?? '') ?> 
                                <br><small><?= htmlspecialchars($po['project_name'] ?? '—') ?></small>
                            </td>
                            <td><?= htmlspecialchars($po['created_by_name'] ?? '—') ?></td>
                            <td><?= date('d M Y', strtotime($po['created_at'])) ?></td>
                            <td><strong><?= $po['item_count'] ?></strong> items</td>
                            <td>₹ <?= number_format($po['total_basic'], 2) ?></td>
                            <td><strong>₹ <?= number_format($po['grand_total'], 2) ?></strong></td>
                            <td class="action-btns" style="text-align:center;">
                                <a href="view_po_from_client.php?id=<?= $po['id'] ?>" class="btn-view" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <!-- You can add Edit later if needed -->
                                <!-- <a href="edit_po_from_client.php?id=<?= $po['id'] ?>" class="btn-edit"><i class="fas fa-edit"></i></a> -->
                                
                                <a href="po_from_client_list.php?delete=<?= $po['id'] ?>" 
                                   class="btn-delete" 
                                   title="Delete"
                                   onclick="return confirm('Are you sure you want to delete this Purchase Order?')">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function filterTable() {
    const input = document.getElementById("searchInput").value.toLowerCase();
    const rows = document.querySelectorAll("#poTable tbody tr");

    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(input) ? "" : "none";
    });
}
</script>

</body>
</html>

<?php $conn->close(); ?>