<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Edit Supplier - FIXED PATH
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/inventory/suppliers/
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/inventory/suppliers/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Define validate_email function if it doesn't exist
if (!function_exists('validate_email')) {
    function validate_email($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
}

// Define validate_phone function if it doesn't exist
if (!function_exists('validate_phone')) {
    function validate_phone($phone) {
        // Simple phone validation - at least 10 digits
        $phone = preg_replace('/[^0-9+]/', '', $phone);
        return strlen($phone) >= 10;
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define csrf_field function if it doesn't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Define verify_csrf_token function if it doesn't exist
if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

// Define begin_transaction function if it doesn't exist
if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db) {
                $db->beginTransaction();
            }
        }
    }
}

// Define commit_transaction function if it doesn't exist
if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->commit();
            }
        }
    }
}

// Define rollback_transaction function if it doesn't exist
if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->rollBack();
            }
        }
    }
}

// Define audit_log function if it doesn't exist
if (!function_exists('audit_log')) {
    function audit_log($user_id, $action, $table, $record_id, $old_values = null, $new_values = null) {
        // Simplified audit log - just log to error log
        error_log("AUDIT: User $user_id - $action on $table:$record_id");
    }
}

// Define log_message function if it doesn't exist
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO') {
        error_log("[$level] $message");
    }
}

// Define constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}
if (!defined('AUDIT_UPDATE')) {
    define('AUDIT_UPDATE', 'update');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('inventory.suppliers.manage');
}

// Set page title
$page_title = 'Edit Supplier';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get supplier ID from URL
$supplier_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$supplier_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid supplier ID');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get supplier data
$supplier = [];
if (function_exists('db_fetch_one')) {
    try {
        $supplier = db_fetch_one("SELECT * FROM suppliers WHERE supplier_id = ?", [$supplier_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching supplier: " . $e->getMessage());
    }
}

if (empty($supplier)) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Supplier not found');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Handle form submission
$errors = [];
$form_data = [
    'supplier_code' => $supplier['supplier_code'] ?? '',
    'supplier_name' => $supplier['supplier_name'] ?? '',
    'contact_person' => $supplier['contact_person'] ?? '',
    'email' => $supplier['email'] ?? '',
    'phone' => $supplier['phone'] ?? '',
    'address' => $supplier['address'] ?? '',
    'city' => $supplier['city'] ?? '',
    'country' => $supplier['country'] ?? '',
    'tax_id' => $supplier['tax_id'] ?? '',
    'payment_terms' => $supplier['payment_terms'] ?? '',
    'is_active' => $supplier['is_active'] ?? 1
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        // Get and validate input
        $form_data['supplier_code'] = isset($_POST['supplier_code']) ? strtoupper(sanitize_input($_POST['supplier_code'])) : '';
        $form_data['supplier_name'] = isset($_POST['supplier_name']) ? sanitize_input($_POST['supplier_name']) : '';
        $form_data['contact_person'] = isset($_POST['contact_person']) ? sanitize_input($_POST['contact_person']) : '';
        $form_data['email'] = isset($_POST['email']) ? sanitize_input($_POST['email']) : '';
        $form_data['phone'] = isset($_POST['phone']) ? sanitize_input($_POST['phone']) : '';
        $form_data['address'] = isset($_POST['address']) ? sanitize_input($_POST['address']) : '';
        $form_data['city'] = isset($_POST['city']) ? sanitize_input($_POST['city']) : '';
        $form_data['country'] = isset($_POST['country']) ? sanitize_input($_POST['country']) : '';
        $form_data['tax_id'] = isset($_POST['tax_id']) ? sanitize_input($_POST['tax_id']) : '';
        $form_data['payment_terms'] = isset($_POST['payment_terms']) ? sanitize_input($_POST['payment_terms']) : '';
        $form_data['is_active'] = isset($_POST['is_active']) ? 1 : 0;
        
        // Validate required fields
        if (empty($form_data['supplier_code'])) {
            $errors[] = 'Supplier code is required';
        } elseif (strlen($form_data['supplier_code']) > 20) {
            $errors[] = 'Supplier code must not exceed 20 characters';
        }
        
        if (empty($form_data['supplier_name'])) {
            $errors[] = 'Supplier name is required';
        } elseif (strlen($form_data['supplier_name']) > 100) {
            $errors[] = 'Supplier name must not exceed 100 characters';
        }
        
        if (!empty($form_data['email']) && !validate_email($form_data['email'])) {
            $errors[] = 'Invalid email format';
        }
        
        if (!empty($form_data['phone']) && !validate_phone($form_data['phone'])) {
            $errors[] = 'Invalid phone number format';
        }
        
        // Check uniqueness
        if (empty($errors) && function_exists('db_fetch_value')) {
            try {
                $exists = db_fetch_value("SELECT COUNT(*) FROM suppliers WHERE supplier_code = ? AND supplier_id != ?", 
                                         [$form_data['supplier_code'], $supplier_id]) ?: 0;
                if ($exists > 0) {
                    $errors[] = 'Supplier code already exists';
                }
            } catch (Exception $e) {
                error_log("Error checking supplier code: " . $e->getMessage());
            }
        }
        
        // Update supplier
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                $update_data = [
                    'supplier_code' => $form_data['supplier_code'],
                    'supplier_name' => $form_data['supplier_name'],
                    'contact_person' => $form_data['contact_person'] ?: null,
                    'email' => $form_data['email'] ?: null,
                    'phone' => $form_data['phone'] ?: null,
                    'address' => $form_data['address'] ?: null,
                    'city' => $form_data['city'] ?: null,
                    'country' => $form_data['country'] ?: null,
                    'tax_id' => $form_data['tax_id'] ?: null,
                    'payment_terms' => $form_data['payment_terms'] ?: null,
                    'is_active' => $form_data['is_active']
                ];
                
                if (function_exists('db_update')) {
                    db_update('suppliers', $update_data, 'supplier_id = ?', [$supplier_id]);
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, AUDIT_UPDATE, 'suppliers', $supplier_id, $supplier, $update_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Supplier updated successfully');
                }
                
                if (function_exists('redirect')) {
                    redirect('view.php?id=' . $supplier_id);
                } else {
                    header('Location: view.php?id=' . $supplier_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to update supplier: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Supplier update failed: " . $e->getMessage(), 'ERROR');
                }
            }
        }
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Edit Supplier</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Edit Supplier</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Edit Supplier: <?php echo escape_html($supplier['supplier_name'] ?? ''); ?></h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/inventory/dashboard.php">Inventory</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Suppliers</a></li>
                    <li class="breadcrumb-item"><a href="view.php?id=<?php echo $supplier_id; ?>">View</a></li>
                    <li class="breadcrumb-item active">Edit</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Error Messages -->
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        <strong>Please fix the following errors:</strong>
                        <ul class="mt-2 mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Edit Form -->
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit me-1"></i>
                            Edit Supplier
                        </h3>
                    </div>
                    
                    <form method="POST" id="editForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="supplier_code">Supplier Code <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="supplier_code" name="supplier_code" 
                                               value="<?php echo escape_html($form_data['supplier_code']); ?>" 
                                               maxlength="20" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="supplier_name">Supplier Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="supplier_name" name="supplier_name" 
                                               value="<?php echo escape_html($form_data['supplier_name']); ?>" 
                                               maxlength="100" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="contact_person">Contact Person</label>
                                <input type="text" class="form-control" id="contact_person" name="contact_person" 
                                       value="<?php echo escape_html($form_data['contact_person']); ?>">
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="email">Email</label>
                                        <input type="email" class="form-control" id="email" name="email" 
                                               value="<?php echo escape_html($form_data['email']); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="phone">Phone</label>
                                        <input type="tel" class="form-control" id="phone" name="phone" 
                                               value="<?php echo escape_html($form_data['phone']); ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="address">Address</label>
                                <input type="text" class="form-control" id="address" name="address" 
                                       value="<?php echo escape_html($form_data['address']); ?>">
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="city">City</label>
                                        <input type="text" class="form-control" id="city" name="city" 
                                               value="<?php echo escape_html($form_data['city']); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="country">Country</label>
                                        <input type="text" class="form-control" id="country" name="country" 
                                               value="<?php echo escape_html($form_data['country']); ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="tax_id">Tax ID / VAT Number</label>
                                        <input type="text" class="form-control" id="tax_id" name="tax_id" 
                                               value="<?php echo escape_html($form_data['tax_id']); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="payment_terms">Payment Terms</label>
                                        <select class="form-select" id="payment_terms" name="payment_terms">
                                            <option value="">Select Terms</option>
                                            <option value="Net 15" <?php echo ($form_data['payment_terms'] ?? '') == 'Net 15' ? 'selected' : ''; ?>>Net 15</option>
                                            <option value="Net 30" <?php echo ($form_data['payment_terms'] ?? '') == 'Net 30' ? 'selected' : ''; ?>>Net 30</option>
                                            <option value="Net 45" <?php echo ($form_data['payment_terms'] ?? '') == 'Net 45' ? 'selected' : ''; ?>>Net 45</option>
                                            <option value="Net 60" <?php echo ($form_data['payment_terms'] ?? '') == 'Net 60' ? 'selected' : ''; ?>>Net 60</option>
                                            <option value="Due on receipt" <?php echo ($form_data['payment_terms'] ?? '') == 'Due on receipt' ? 'selected' : ''; ?>>Due on receipt</option>
                                            <option value="2/10, Net 30" <?php echo ($form_data['payment_terms'] ?? '') == '2/10, Net 30' ? 'selected' : ''; ?>>2/10, Net 30</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mb-3">
                                <div class="form-check form-switch">
                                    <input type="checkbox" class="form-check-input" id="is_active" name="is_active"
                                           <?php echo !empty($form_data['is_active']) ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="is_active">Active</label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save me-1"></i> Update Supplier
                            </button>
                            <a href="view.php?id=<?php echo $supplier_id; ?>" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Auto-capitalize supplier code
    $('#supplier_code').on('input', function() {
        this.value = this.value.toUpperCase();
    });
    
    // Check code availability
    let codeTimeout;
    $('#supplier_code').on('input', function() {
        clearTimeout(codeTimeout);
        const code = $(this).val();
        const originalCode = '<?php echo addslashes($supplier['supplier_code'] ?? ''); ?>';
        
        if (code.length < 2 || code === originalCode) return;
        
        codeTimeout = setTimeout(function() {
            $.get('/HMSPOS/api/check-supplier-code.php', { 
                code: code,
                exclude: <?php echo $supplier_id; ?>
            }, function(response) {
                const $code = $('#supplier_code');
                if (response.exists) {
                    $code.addClass('is-invalid');
                    if ($code.next('.invalid-feedback').length === 0) {
                        $code.after('<div class="invalid-feedback">Supplier code already exists</div>');
                    }
                } else {
                    $code.removeClass('is-invalid');
                    $code.next('.invalid-feedback').remove();
                }
            }).fail(function() {
                console.error('Failed to check supplier code');
            });
        }, 500);
    });
});
</script>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>