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

// ------------------- ACCESS CONTROL ------------------- //
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    $accessDenied = true;
} else {
    $accessDenied = false;
}

// Check if ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $invalidId = true;
} else {
    $invalidId = false;
    $id = intval($_GET['id']);
    
    // Fetch supplier
    $stmt = $pdo->prepare("SELECT * FROM suppliers WHERE id = ?");
    $stmt->execute([$id]);
    $supplier = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$supplier) {
        $notFound = true;
    } else {
        $notFound = false;
    }
}

// ------------------- FORM HANDLING ------------------- //
$errors = [];
$success = '';
$name = $supplier['name'] ?? '';
$contact = $supplier['contact'] ?? '';
$email = $supplier['email'] ?? '';
$address = $supplier['address'] ?? '';
$redirect = false;
$redirectUrl = '';

if (!$accessDenied && !$invalidId && !$notFound && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $contact = trim($_POST['contact'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');

    // 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 (excluding current supplier)
    if (empty($errors) && $name && $name !== $supplier['name']) {
        $checkStmt = $pdo->prepare("SELECT id FROM suppliers WHERE name = ? AND id != ?");
        $checkStmt->execute([$name, $id]);
        if ($checkStmt->fetch()) {
            $errors[] = 'Another supplier with this name already exists.';
        }
    }

    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("UPDATE suppliers SET name = ?, contact = ?, email = ?, address = ? WHERE id = ?");
            $stmt->execute([
                $name, 
                $contact ?: null, 
                $email ?: null, 
                $address ?: null, 
                $id
            ]);
            
            $_SESSION['success_message'] = "Supplier '$name' updated successfully!";
            $redirect = true;
            $redirectUrl = "supplier_list.php?updated=1&id=" . $id;
            
        } catch (PDOException $e) {
            // Check for duplicate entry error
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                $errors[] = 'Another supplier with this name already exists.';
            } else {
                $errors[] = "Database error: " . htmlspecialchars($e->getMessage());
            }
        }
    }
}

// Handle redirect after successful update
if ($redirect && !headers_sent()) {
    header("Location: " . $redirectUrl);
    exit;
}

// ------------------- INCLUDE HEADER & SIDEBAR ------------------- //
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

// Display access denied message
if ($accessDenied) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>
                <i class='fas fa-ban'></i> Access denied. Admin privileges required.
            </div>
          </div>";
    require_once '../includes/footer.php';
    exit;
}

// Display invalid ID message
if ($invalidId) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>
                <i class='fas fa-exclamation-triangle'></i> Invalid supplier ID.
            </div>
            <a href='supplier_list.php' class='btn btn-secondary'>Back to Suppliers</a>
          </div>";
    require_once '../includes/footer.php';
    exit;
}

// Display not found message
if ($notFound) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-warning'>
                <i class='fas fa-search'></i> Supplier not found.
            </div>
            <a href='supplier_list.php' class='btn btn-secondary'>Back to Suppliers</a>
          </div>";
    require_once '../includes/footer.php';
    exit;
}

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

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="text-primary">
            <i class="fas fa-edit"></i> Edit Supplier
        </h3>
        <div>
            <span class="badge badge-info">ID: <?= $id ?></span>
            <span class="badge badge-secondary ml-2">
                Created: <?= date('d/m/Y', strtotime($supplier['created_at'])) ?>
            </span>
        </div>
    </div>

    <!-- Success Message -->
    <?php if ($success): ?>
        <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">
                <i class="fas fa-truck"></i> Supplier Information
            </h5>
        </div>
        <div class="card-body">
            <form method="POST" id="editSupplierForm">
                <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>
                
                <!-- Additional Info (Readonly) -->
                <div class="row mt-4">
                    <div class="col-md-12">
                        <div class="card bg-light">
                            <div class="card-body py-2">
                                <small class="text-muted">
                                    <i class="fas fa-info-circle"></i> 
                                    Supplier ID: <?= $id ?> | 
                                    Created: <?= date('F d, Y H:i', strtotime($supplier['created_at'])) ?>
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="form-group mt-4">
                    <button type="submit" class="btn btn-success btn-lg">
                        <i class="fas fa-save"></i> Update Supplier
                    </button>
                    <a href="supplier_list.php" class="btn btn-secondary btn-lg">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                    <a href="javascript:history.back()" class="btn btn-outline-info btn-lg">
                        <i class="fas fa-arrow-left"></i> Back
                    </a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Supplier Statistics -->
    <?php
    // Get purchase statistics for this supplier
    $purchaseStmt = $pdo->prepare("
        SELECT COUNT(*) as total_purchases, 
               COALESCE(SUM(total), 0) as total_amount 
        FROM purchases 
        WHERE supplier_id = ?
    ");
    $purchaseStmt->execute([$id]);
    $stats = $purchaseStmt->fetch(PDO::FETCH_ASSOC);
    ?>
    
    <div class="card mt-4">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-chart-bar"></i> Supplier Statistics</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <div class="alert alert-info">
                        <h6><i class="fas fa-shopping-cart"></i> Total Purchases</h6>
                        <h4><?= $stats['total_purchases'] ?></h4>
                        <small class="text-muted">Number of purchase orders</small>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="alert alert-success">
                        <h6><i class="fas fa-money-bill-wave"></i> Total Purchase Value</h6>
                        <h4>TSh <?= number_format($stats['total_amount'], 2) ?></h4>
                        <small class="text-muted">Total amount from purchases</small>
                    </div>
                </div>
            </div>
            <?php if ($stats['total_purchases'] > 0): ?>
                <div class="text-center mt-2">
                    <a href="../purchases/index.php?supplier_id=<?= $id ?>" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-eye"></i> View Purchase History
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Form validation
document.getElementById('editSupplierForm').addEventListener('submit', function(e) {
    const nameField = document.getElementById('name');
    const contactField = document.getElementById('contact');
    const emailField = document.getElementById('email');
    
    let isValid = true;
    
    // Name validation
    if (nameField.value.trim() === '') {
        alert('Supplier name is required.');
        nameField.focus();
        isValid = false;
    } else if (nameField.value.length > 200) {
        alert('Supplier name must be less than 200 characters.');
        nameField.focus();
        isValid = false;
    }
    
    // Contact validation
    if (contactField.value.length > 100) {
        alert('Contact information must be less than 100 characters.');
        contactField.focus();
        isValid = false;
    }
    
    // Email validation
    if (emailField.value && emailField.value.length > 100) {
        alert('Email must be less than 100 characters.');
        emailField.focus();
        isValid = false;
    } else if (emailField.value && !validateEmail(emailField.value)) {
        alert('Please enter a valid email address.');
        emailField.focus();
        isValid = false;
    }
    
    if (!isValid) {
        e.preventDefault();
    }
});

function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

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

// Auto-focus on name field
document.getElementById('name').focus();
</script>

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