<?php
include 'db.php';

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get form data
    $supplier_id = $_POST['supplier_id'];
    $name = trim($_POST['name']);
    $contact_number = trim($_POST['contact_number']);
    $email = trim($_POST['email']);
    $address = trim($_POST['address']);
    $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
    
    // Validate required fields
    if (empty($name)) {
        header("Location: supplier-list.php?error=name_required");
        exit();
    }
    
    // Validate email if provided
    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header("Location: supplier-list.php?error=invalid_email");
        exit();
    }
    
    // Check if supplier exists
    $check_query = "SELECT id FROM vendors WHERE id = ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("i", $supplier_id);
    $check_stmt->execute();
    $result = $check_stmt->get_result();
    
    if ($result->num_rows == 0) {
        header("Location: supplier-list.php?error=supplier_not_found");
        exit();
    }
    
    // Update supplier
    $update_query = "UPDATE vendors SET name = ?, contact_number = ?, email = ?, address = ?, is_active = ? WHERE id = ?";
    $update_stmt = $conn->prepare($update_query);
    $update_stmt->bind_param("ssssii", $name, $contact_number, $email, $address, $is_active, $supplier_id);
    
    if ($update_stmt->execute()) {
        // Success
        header("Location: supplier-list.php?updated=1");
        exit();
    } else {
        // Error
        header("Location: supplier-list.php?error=update_failed");
        exit();
    }
} else {
    // If not POST request, redirect to supplier list
    header("Location: supplier-list.php");
    exit();
}
?>
