<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$buyerSystem = new BuyerSystem($database, $currentUserId);

if (!$buyerSystem->hasPermission('quality_specifications')) {
    $_SESSION['flash_message'] = 'Quality specifications are only available for Processors and Exporters';
    $_SESSION['flash_type'] = 'warning';
    header('Location: ' . APP_URL . '/buyer/dashboard.php');
    exit();
}

// Handle create/update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        if ($_POST['action'] === 'create' || $_POST['action'] === 'update') {
            $sql = $_POST['action'] === 'create' 
                ? "INSERT INTO quality_specifications (buyer_id, product_type, specification_name, 
                    moisture_content, purity_level, color_grade, size_requirements, 
                    packaging_requirements, additional_requirements, is_default, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())"
                : "UPDATE quality_specifications SET product_type = ?, specification_name = ?,
                    moisture_content = ?, purity_level = ?, color_grade = ?, size_requirements = ?,
                    packaging_requirements = ?, additional_requirements = ?, is_default = ?,
                    updated_at = NOW() WHERE id = ? AND buyer_id = ?";
            
            $stmt = $db->prepare($sql);
            
            if ($_POST['action'] === 'create') {
                $stmt->execute([
                    $currentUserId,
                    $_POST['product_type'],
                    $_POST['specification_name'],
                    $_POST['moisture_content'],
                    $_POST['purity_level'],
                    $_POST['color_grade'],
                    $_POST['size_requirements'],
                    $_POST['packaging_requirements'],
                    $_POST['additional_requirements'],
                    isset($_POST['is_default']) ? 1 : 0
                ]);
            } else {
                $stmt->execute([
                    $_POST['product_type'],
                    $_POST['specification_name'],
                    $_POST['moisture_content'],
                    $_POST['purity_level'],
                    $_POST['color_grade'],
                    $_POST['size_requirements'],
                    $_POST['packaging_requirements'],
                    $_POST['additional_requirements'],
                    isset($_POST['is_default']) ? 1 : 0,
                    $_POST['spec_id'],
                    $currentUserId
                ]);
            }
            
            $_SESSION['flash_message'] = 'Quality specification saved successfully';
            $_SESSION['flash_type'] = 'success';
        }
    } catch (Exception $e) {
        $_SESSION['flash_message'] = 'Error: ' . $e->getMessage();
        $_SESSION['flash_type'] = 'error';
    }
    
    header('Location: ' . APP_URL . '/buyer/quality-specs.php');
    exit();
}

// Get specifications
$sql = "SELECT * FROM quality_specifications WHERE buyer_id = ? ORDER BY is_default DESC, created_at DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$specifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Quality Specifications';
$breadcrumbs = [['title' => 'Quality Specifications', 'url' => '']];

require_once __DIR__ . '/includes/base.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<div class="row mb-4">
    <div class="col">
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createSpecModal">
            <i class="bi bi-plus-circle me-2"></i>New Specification
        </button>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0"><i class="bi bi-clipboard-check me-2"></i>Quality Specifications (<?php echo count($specifications); ?>)</h5>
    </div>
    <div class="card-body">
        <?php if (empty($specifications)): ?>
            <div class="text-center py-5">
                <i class="bi bi-clipboard-check" style="font-size: 4rem; color: #d1d5db;"></i>
                <h5 class="mt-3 text-muted">No specifications yet</h5>
                <p class="text-muted">Define quality requirements for your products</p>
            </div>
        <?php else: ?>
            <div class="row g-3">
                <?php foreach ($specifications as $spec): ?>
                <div class="col-md-6">
                    <div class="card h-100 <?php echo $spec['is_default'] ? 'border-primary' : ''; ?>">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <div>
                                    <h6 class="mb-1"><?php echo htmlspecialchars($spec['specification_name']); ?></h6>
                                    <span class="badge bg-secondary"><?php echo htmlspecialchars($spec['product_type']); ?></span>
                                    <?php if ($spec['is_default']): ?>
                                    <span class="badge bg-primary">Default</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <td class="text-muted">Moisture Content:</td>
                                    <td><strong><?php echo htmlspecialchars($spec['moisture_content'] ?? 'N/A'); ?></strong></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Purity Level:</td>
                                    <td><strong><?php echo htmlspecialchars($spec['purity_level'] ?? 'N/A'); ?></strong></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Color Grade:</td>
                                    <td><strong><?php echo htmlspecialchars($spec['color_grade'] ?? 'N/A'); ?></strong></td>
                                </tr>
                                <?php if (!empty($spec['size_requirements'])): ?>
                                <tr>
                                    <td class="text-muted">Size:</td>
                                    <td><strong><?php echo htmlspecialchars($spec['size_requirements']); ?></strong></td>
                                </tr>
                                <?php endif; ?>
                            </table>
                            
                            <?php if (!empty($spec['packaging_requirements'])): ?>
                            <div class="mt-2">
                                <small class="text-muted">Packaging:</small>
                                <p class="small mb-0"><?php echo htmlspecialchars($spec['packaging_requirements']); ?></p>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Create Specification Modal -->
<div class="modal fade" id="createSpecModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-clipboard-plus me-2"></i>New Quality Specification</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="create">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Specification Name <span class="text-danger">*</span></label>
                            <input type="text" name="specification_name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Product Type <span class="text-danger">*</span></label>
                            <input type="text" name="product_type" class="form-control" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Moisture Content (%)</label>
                            <input type="text" name="moisture_content" class="form-control" placeholder="e.g., <12%">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Purity Level (%)</label>
                            <input type="text" name="purity_level" class="form-control" placeholder="e.g., >98%">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Color Grade</label>
                            <input type="text" name="color_grade" class="form-control" placeholder="e.g., Grade A">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Size Requirements</label>
                            <input type="text" name="size_requirements" class="form-control" 
                                   placeholder="e.g., 5-7mm diameter">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Packaging Requirements</label>
                            <textarea name="packaging_requirements" class="form-control" rows="2"></textarea>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Additional Requirements</label>
                            <textarea name="additional_requirements" class="form-control" rows="2"></textarea>
                        </div>
                        <div class="col-12">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_default" id="isDefault">
                                <label class="form-check-label" for="isDefault">
                                    Set as default specification for this product type
                                </label>
                            </div>
                        </div>
                    </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">
                        <i class="bi bi-save me-2"></i>Save Specification
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php renderBuyerFooter(); ?>