<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');
session_start();
require_once("../config/config.php");

$success = "";
$error = "";
$search = trim($_GET['search'] ?? '');

// Handle Delete Request
if (isset($_GET['delete'])) {
    $material_id = (int)$_GET['delete'];
    try {
        $query = "DELETE FROM material_master WHERE id = ?";
        $stmt = $pdo->prepare($query);
        if ($stmt->execute([$material_id])) {
            $success = "Material deleted successfully.";
        } else {
            $error = "Failed to delete material.";
        }
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Fetch materials with optional search
try {
    if ($search !== '') {
        $query = "SELECT * FROM material_master 
                  WHERE sku LIKE ? OR name LIKE ? OR category LIKE ? 
                  ORDER BY created_at DESC";
        $stmt = $pdo->prepare($query);
        $like = "%$search%";
        $stmt->execute([$like, $like, $like]);
    } else {
        $query = "SELECT * FROM material_master ORDER BY created_at DESC";
        $stmt = $pdo->prepare($query);
        $stmt->execute();
    }
    $materials = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error = "Database error: " . $e->getMessage();
    $materials = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Material Management</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            background: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.6)),
                        url('../background.jpeg') center/cover no-repeat fixed;
            display: flex;
            flex-direction: column;
            color: white;
        }

        /* Header */
        .page-header {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(12px);
            padding: 40px 20px;
            text-align: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
        }

        .page-header h1 {
            font-size: 36px;
            font-weight: 700;
            text-shadow: 0 2px 10px rgba(0,0,0,0.4);
        }

        .header-actions {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            justify-content: center;
            width: 100%;
        }

        .search-form {
            position: relative;
            max-width: 400px;
            width: 100%;
        }

        .search-input {
            width: 100%;
            padding: 14px 50px 14px 20px;
            background: rgba(255, 255, 255, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 14px;
            color: white;
            font-size: 16px;
            backdrop-filter: blur(8px);
            transition: all 0.3s ease;
        }

        .search-input::placeholder {
            color: rgba(255, 255, 255, 0.6);
        }

        .search-input:focus {
            outline: none;
            border-color: #c4b5fd;
            box-shadow: 0 0 0 4px rgba(196, 181, 253, 0.3);
        }

        .search-btn {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: rgba(255, 255, 255, 0.7);
            cursor: pointer;
            padding: 8px;
            font-size: 20px;
            transition: all 0.3s ease;
        }

        .search-btn:hover {
            color: white;
            transform: translateY(-50%) scale(1.1);
        }

        .add-btn {
            background: white;
            color: #6b21a8;
            padding: 14px 32px;
            border-radius: 14px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s ease;
            box-shadow: 0 8px 20px rgba(0,0,0,0.3);
        }

        .add-btn:hover {
            transform: translateY(-3px);
            background: #f3e8ff;
            box-shadow: 0 12px 25px rgba(0,0,0,0.4);
        }

        /* Main Content */
        main {
            flex: 1;
            padding: 40px 20px;
            max-width: 1400px;
            margin: 0 auto;
            width: 100%;
        }

        /* Messages */
        .message {
            padding: 16px 20px;
            border-radius: 14px;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            font-weight: 600;
            backdrop-filter: blur(8px);
            max-width: 800px;
            margin-left: auto;
            margin-right: auto;
        }

        .success {
            background: rgba(34, 197, 94, 0.25);
            border: 1px solid rgba(74, 222, 128, 0.4);
        }

        .error {
            background: rgba(239, 68, 68, 0.25);
            border: 1px solid rgba(252, 165, 165, 0.4);
        }

        .message i {
            margin-right: 14px;
            font-size: 22px;
        }

        /* Glassmorphism Table Card */
        .glass-card {
            background: rgba(255, 255, 255, 0.12);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            border-radius: 24px;
            border: 1px solid rgba(255, 255, 255, 0.25);
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5);
            overflow: hidden;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        thead {
            background: rgba(255, 255, 255, 0.1);
        }

        th {
            padding: 20px 16px;
            text-align: left;
            font-weight: 600;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: rgba(255, 255, 255, 0.9);
        }

        td {
            padding: 18px 16px;
            font-size: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }

        tbody tr {
            transition: all 0.3s ease;
        }

        tbody tr:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .actions {
            display: flex;
            gap: 16px;
        }

        .action-icon {
            font-size: 18px;
            transition: all 0.3s ease;
        }

        .action-view { color: #60a5fa; }
        .action-view:hover { color: #93c5fd; transform: scale(1.2); }

        .action-edit { color: #c4b5fd; }
        .action-edit:hover { color: #ddd6fe; transform: scale(1.2); }

        .action-delete { color: #fca5a5; }
        .action-delete:hover { color: #fdb4b4; transform: scale(1.2); }

        .low-stock {
            background: rgba(239, 68, 68, 0.2);
            color: #fca5a5;
            padding: 4px 10px;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 600;
        }

        .normal-stock {
            color: rgba(255, 255, 255, 0.7);
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 80px 40px;
        }

        .empty-state i {
            font-size: 80px;
            color: rgba(255, 255, 255, 0.3);
            margin-bottom: 24px;
        }

        .empty-state h3 {
            font-size: 28px;
            margin-bottom: 16px;
        }

        .empty-state p {
            font-size: 16px;
            color: rgba(255, 255, 255, 0.7);
            margin-bottom: 32px;
        }

        .empty-btn {
            background: linear-gradient(135deg, #8b5cf6, #a78bfa);
            color: white;
            padding: 16px 40px;
            border-radius: 14px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 12px;
            box-shadow: 0 10px 30px rgba(139, 92, 246, 0.4);
            transition: all 0.4s ease;
        }

        .empty-btn:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(139, 92, 246, 0.5);
        }

        /* Responsive */
        @media (max-width: 992px) {
            th, td {
                padding: 14px 10px;
                font-size: 14px;
            }
        }

        @media (max-width: 768px) {
            .page-header h1 {
                font-size: 30px;
            }
            .header-actions {
                flex-direction: column;
                align-items: center;
            }
            .search-form {
                max-width: 300px;
            }
            .actions {
                gap: 12px;
            }
            .action-icon {
                font-size: 16px;
            }
        }

        @media (max-width: 640px) {
            table {
                display: block;
                overflow-x: auto;
                white-space: nowrap;
            }
        }
    </style>
</head>
<body>
    <!-- Page Header -->
    <header class="page-header">
        <div class="header-content">
            <h1>Material Management</h1>
            <div class="header-actions">
                <form action="" method="get" class="search-form">
                    <input type="text" name="search" class="search-input" placeholder="Search by SKU, name or category..." 
                           value="<?= htmlspecialchars($search) ?>">
                    <button type="submit" class="search-btn">
                        <i class="fas fa-search"></i>
                    </button>
                </form>
                <a href="add-material.php" class="add-btn">
                    <i class="fas fa-plus"></i> Add New Material
                </a>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main>
        <?php if (!empty($success)): ?>
            <div class="message success">
                <i class="fas fa-check-circle"></i>
                <?= htmlspecialchars($success) ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
            <div class="message error">
                <i class="fas fa-exclamation-triangle"></i>
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <div class="glass-card">
            <?php if (count($materials) > 0): ?>
                <div style="overflow-x: auto;">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>SKU</th>
                                <th>Name</th>
                                <th>Category</th>
                                <th>Unit</th>
                                <th>Stock</th>
                                <th>Reorder Level</th>
                                <th>Last Cost</th>
                                <th>Created</th>
                                <th style="text-align: center;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($materials as $material): ?>
                                <tr>
                                    <td><?= htmlspecialchars($material['id']) ?></td>
                                    <td style="font-weight: 600;"><?= htmlspecialchars($material['sku']) ?></td>
                                    <td><?= htmlspecialchars($material['name']) ?></td>
                                    <td><?= htmlspecialchars($material['category'] ?? '<span class="normal-stock">—</span>') ?></td>
                                    <td><?= htmlspecialchars($material['unit']) ?></td>
                                    <td>
                                        <?php if ($material['stock'] <= $material['reorder_level'] && $material['reorder_level'] > 0): ?>
                                            <span class="low-stock"><?= number_format($material['stock'], 3) ?></span>
                                        <?php else: ?>
                                            <?= number_format($material['stock'], 3) ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= number_format($material['reorder_level'], 3) ?></td>
                                    <td><?= number_format($material['last_cost'], 2) ?></td>
                                    <td><?= date('d M Y', strtotime($material['created_at'])) ?></td>
                                    <td>
                                        <div class="actions">
                                            <a href="view-material.php?id=<?= $material['id'] ?>" class="action-icon action-view" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="edit-material.php?id=<?= $material['id'] ?>" class="action-icon action-edit" title="Edit Material">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="?delete=<?= $material['id'] ?>&search=<?= urlencode($search) ?>" 
                                               onclick="return confirm('Are you sure you want to delete this material?\n\nSKU: <?= addslashes(htmlspecialchars($material['sku'])) ?> - <?= addslashes(htmlspecialchars($material['name'])) ?>');"
                                               class="action-icon action-delete" title="Delete Material">
                                                <i class="fas fa-trash-alt"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    <i class="fas fa-boxes"></i>
                    <h3>
                        <?php if ($search !== ''): ?>
                            No materials found matching "<?= htmlspecialchars($search) ?>"
                        <?php else: ?>
                            No Materials Found
                        <?php endif; ?>
                    </h3>
                    <p>
                        <?php if ($search !== ''): ?>
                            Try adjusting your search terms or add a new material.
                        <?php else: ?>
                            Get started by adding your first material to the inventory.
                        <?php endif; ?>
                    </p>
                    <a href="add-material.php" class="empty-btn">
                        <i class="fas fa-plus"></i> Add Your First Material
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </main>
</body>
</html>