<?php 
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Get customer ID from URL parameter
$customer_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($customer_id <= 0) {
    $_SESSION['error_message'] = "Invalid customer ID";
    header("Location: all_customers.php");
    exit();
}

// Fetch customer data
$query = "SELECT * FROM customers WHERE customer_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Customer not found";
    header("Location: all_customers.php");
    exit();
}

$customer = $result->fetch_assoc();
?>

<!doctype html>
<html lang="en" data-layout="vertical" data-topbar="light" data-sidebar="dark" data-sidebar-size="lg" data-sidebar-image="none" data-preloader="disable">

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Customer')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <style>
        .form-card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        .form-card:hover {
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
        }
        .card-header-custom {
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 15px 20px;
            border-radius: 10px 10px 0 0;
        }
        .required-field::after {
            content: "*";
            color: #dc3545;
            margin-left: 4px;
        }
        .form-control, .form-select {
            padding: 0.5rem 0.75rem;
            border-radius: 0.25rem;
        }
        .action-buttons {
            padding: 15px 0;
            border-top: 1px solid #e9ecef;
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Customer Management', 'title' => 'Edit Customer')); ?>

                    <!-- Display success/error messages if they exist -->
                    <?php if(isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if(isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <form id="editCustomerForm" method="POST" action="update_customer.php">
                                <input type="hidden" name="customer_id" value="<?php echo $customer_id; ?>">
                                
                                <div class="row">
                                    <!-- Customer Information Card -->
                                    <div class="col-lg-6">
                                        <div class="card form-card mb-4">
                                            <div class="card-header-custom">
                                                <h5 class="mb-0">
                                                    <i class="ri-user-line me-2"></i>Customer Information
                                                </h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="mb-3">
                                                    <label for="first_name" class="form-label required-field">First Name/Company Name</label>
                                                    <input type="text" class="form-control" id="first_name" name="first_name" 
                                                          value="<?php echo htmlspecialchars($customer['first_name']); ?>" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="last_name" class="form-label">Last Name</label>
                                                    <input type="text" class="form-control" id="last_name" name="last_name" 
                                                          value="<?php echo htmlspecialchars($customer['last_name']); ?>">
                                                </div>
                                                <div class="mb-3">
                                                    <label for="email" class="form-label">Email</label>
                                                    <div class="input-group">
                                                        <input type="email" class="form-control" id="email" name="email" 
                                                              value="<?php echo htmlspecialchars($customer['email']); ?>">
                                                        <span class="input-group-text"><i class="ri-mail-line"></i></span>
                                                    </div>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="phone_number" class="form-label">Phone Number</label>
                                                    <div class="input-group">
                                                        <input type="tel" class="form-control" id="phone_number" name="phone_number" 
                                                              value="<?php echo htmlspecialchars($customer['phone_number']); ?>">
                                                        <span class="input-group-text"><i class="ri-phone-line"></i></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Address & Status Card -->
                                    <div class="col-lg-6">
                                        <div class="card form-card mb-4">
                                            <div class="card-header-custom">
                                                <h5 class="mb-0">
                                                    <i class="ri-map-pin-line me-2"></i>Address & Status
                                                </h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="mb-3">
                                                    <label for="address" class="form-label">Address</label>
                                                    <textarea class="form-control" id="address" name="address" rows="3"><?php echo htmlspecialchars($customer['address']); ?></textarea>
                                                </div>
                                                
                                                <div class="row mb-3">
                                                    <div class="col-md-6">
                                                        <label for="city" class="form-label">City</label>
                                                        <input type="text" class="form-control" id="city" name="city" 
                                                              value="<?php echo htmlspecialchars($customer['city']); ?>">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="postal_code" class="form-label">Postal Code</label>
                                                        <input type="text" class="form-control" id="postal_code" name="postal_code" 
                                                              value="<?php echo htmlspecialchars($customer['postal_code']); ?>">
                                                    </div>
                                                </div>
                                                
                                                <div class="row mb-3">
                                                    <div class="col-md-6">
                                                        <label for="country" class="form-label">Country</label>
                                                        <input type="text" class="form-control" id="country" name="country" 
                                                              value="<?php echo htmlspecialchars($customer['country']); ?>">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="status" class="form-label">Account Status</label>
                                                        <select class="form-select w-50" id="status" name="status">
                                                            <option value="1" <?php echo $customer['status'] == 1 ? 'selected' : ''; ?>>Active</option>
                                                            <option value="0" <?php echo $customer['status'] == 0 ? 'selected' : ''; ?>>Inactive</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Action Buttons -->
                                    <div class="col-12">
                                        <div class="card form-card">
                                            <div class="card-body">
                                                <div class="action-buttons text-end">
                                                    <a href="all_customers.php" class="btn btn-light me-2">
                                                        <i class="ri-arrow-left-line align-bottom me-1"></i> Cancel
                                                    </a>
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="ri-save-line align-bottom me-1"></i> Update Customer
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Form validation
        $('#editCustomerForm').on('submit', function(e) {
            if (!$('#first_name').val().trim()) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    text: 'First Name/Company Name is required',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: true
                });
                return false;
            }
            
            // Phone number validation (optional)
            const phoneNumber = $('#phone_number').val().trim();
            if (phoneNumber && !/^[0-9+\-\s()]*$/.test(phoneNumber)) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Phone Number',
                    text: 'Please enter a valid phone number',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false,
                    showCloseButton: true
                });
                return false;
            }
            
            return true;
        });
    });
    </script>
</body>
</html>