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

// Role guard - only admin can add suppliers
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    $accessDenied = true;
} else {
    $accessDenied = false;
}

$errors = [];
$name = '';
$contact = '';
$email = '';
$address = '';
$success = '';
$redirect = false;
$redirectUrl = '';

// Check for existing success message
if (isset($_SESSION['success_message'])) {
    $success = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

if (!$accessDenied && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $contact = trim($_POST['contact'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    
    // Basic validation
    if (empty($name)) {
        $errors[] = 'Supplier name is required.';
    } elseif (strlen($name) > 200) {
        $errors[] = 'Supplier name must be less than 200 characters.';
    }
    
    if ($contact && strlen($contact) > 100) {
        $errors[] = 'Contact information must be less than 100 characters.';
    }
    
    if ($email) {
        if (strlen($email) > 100) {
            $errors[] = 'Email must be less than 100 characters.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Please enter a valid email address.';
        }
    }
    
    // Check for duplicate supplier name ONLY if validation passed
    if (empty($errors) && $name) {
        $checkStmt = $pdo->prepare("SELECT id FROM suppliers WHERE name = ?");
        $checkStmt->execute([$name]);
        if ($checkStmt->fetch()) {
            $errors[] = 'A supplier with this name already exists.';
        }
    }
    
    // If no errors, insert the new supplier
    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO suppliers (name, contact, email, address, created_at) 
                                   VALUES (?, ?, ?, ?, NOW())");
            $stmt->execute([
                $name, 
                $contact ?: null, 
                $email ?: null, 
                $address ?: null
            ]);
            
            $supplierId = $pdo->lastInsertId();
            $_SESSION['success_message'] = "Supplier '$name' added successfully! (ID: $supplierId)";
            
            // Redirect to avoid form resubmission
            $redirect = true;
            $redirectUrl = "index.php?added=1&id=" . $supplierId;
            
        } catch (PDOException $e) {
            // Check if error is due to duplicate entry
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                $errors[] = 'A supplier with this name already exists.';
            } else {
                $errors[] = "Database error: " . htmlspecialchars($e->getMessage());
            }
        }
    }
}

// Check if we need to redirect
if ($redirect && !headers_sent()) {
    header("Location: " . $redirectUrl);
    exit;
}

// Now include the HTML parts
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

// Check if access was denied after including headers
if ($accessDenied) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'><div class='alert alert-danger'>Access denied. Admin privileges required.</div></div>";
    require_once '../includes/footer.php';
    exit;
}
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <h3 class="text-success mb-4">
        <i class="fas fa-plus-circle"></i> Add New Supplier
    </h3>
    
    <!-- Success message from current submission or previous page -->
    <?php if ($success && empty($errors)): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    <?php endif; ?>
    
    <!-- Error messages -->
    <?php if ($errors): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <h5 class="alert-heading"><i class="fas fa-exclamation-triangle"></i> Please fix the following errors:</h5>
            <ul class="mb-0">
                <?php foreach ($errors as $error): ?>
                    <li><?= htmlspecialchars($error) ?></li>
                <?php endforeach; ?>
            </ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    <?php endif; ?>
    
    <div class="card">
        <div class="card-header bg-light">
            <h5 class="mb-0">Supplier Information</h5>
        </div>
        <div class="card-body">
            <form method="POST" id="supplierForm">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="name" class="font-weight-bold">
                                Supplier Name <span class="text-danger">*</span>
                            </label>
                            <input type="text" 
                                   name="name" 
                                   id="name" 
                                   class="form-control" 
                                   value="<?= htmlspecialchars($name) ?>" 
                                   required
                                   maxlength="200"
                                   placeholder="Enter supplier name"
                                   autofocus>
                            <small class="form-text text-muted">Required. Maximum 200 characters.</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="contact" class="font-weight-bold">
                                Contact Person / Phone
                            </label>
                            <input type="text" 
                                   name="contact" 
                                   id="contact" 
                                   class="form-control" 
                                   value="<?= htmlspecialchars($contact) ?>"
                                   maxlength="100"
                                   placeholder="e.g., John Doe / +255 712 345 678">
                            <small class="form-text text-muted">Maximum 100 characters.</small>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="email" class="font-weight-bold">
                                Email Address
                            </label>
                            <input type="email" 
                                   name="email" 
                                   id="email" 
                                   class="form-control" 
                                   value="<?= htmlspecialchars($email) ?>"
                                   maxlength="100"
                                   placeholder="supplier@example.com">
                            <small class="form-text text-muted">Maximum 100 characters.</small>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="address" class="font-weight-bold">
                        Address
                    </label>
                    <textarea name="address" 
                              id="address" 
                              class="form-control" 
                              rows="3"
                              placeholder="Enter complete address including postal address if available"><?= htmlspecialchars($address) ?></textarea>
                </div>
                
                <div class="form-group mt-4">
                    <button type="submit" class="btn btn-success btn-lg">
                        <i class="fas fa-save"></i> Save Supplier
                    </button>
                    <a href="supplier_list.php" class="btn btn-secondary btn-lg">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                    <button type="reset" class="btn btn-outline-info btn-lg" onclick="clearForm()">
                        <i class="fas fa-redo"></i> Clear Form
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <div class="card mt-4">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-lightbulb"></i> Tips</h5>
        </div>
        <div class="card-body">
            <ul class="mb-0">
                <li><strong>Supplier names must be unique</strong> - The system will check for duplicates</li>
                <li>All fields except supplier name are optional</li>
                <li>You can edit supplier information at any time from the suppliers list</li>
                <li>After successful submission, you'll be redirected to avoid duplicate entries</li>
            </ul>
        </div>
    </div>
</div>

<script>
function clearForm() {
    if (confirm('Are you sure you want to clear all fields?')) {
        document.getElementById('supplierForm').reset();
        document.getElementById('name').focus();
    }
}

// Prevent form resubmission on page refresh
if (window.history.replaceState) {
    window.history.replaceState(null, null, window.location.href);
}
</script>

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