<?php
session_start();
include 'layouts/dbconn.php';
include 'menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

$success_message = '';
$error_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $date_of_birth = !empty($_POST['date_of_birth']) ? $_POST['date_of_birth'] : null;
    $gender = $_POST['gender'];
    $customer_type = $_POST['customer_type'];
    $notes = trim($_POST['notes']);
    
    // Validation
    if (empty($first_name) || empty($last_name) || empty($phone)) {
        $error_message = "First name, last name, and phone number are required.";
    } else {
        // Check if phone number already exists
        $check_phone_sql = "SELECT customer_id FROM customers WHERE phone = ?";
        $check_stmt = $conn->prepare($check_phone_sql);
        $check_stmt->bind_param("s", $phone);
        $check_stmt->execute();
        $existing_customer = $check_stmt->get_result()->fetch_assoc();
        
        if ($existing_customer) {
            $error_message = "A customer with this phone number already exists.";
        } else {
            // Insert new customer
            $insert_sql = "INSERT INTO customers (first_name, last_name, email, phone, address, 
                          date_of_birth, gender, customer_type, notes, created_by) 
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("sssssssssi", $first_name, $last_name, $email, $phone, 
                             $address, $date_of_birth, $gender, $customer_type, $notes, $user_id);
            
            if ($stmt->execute()) {
                $customer_id = $conn->insert_id;
                
                // Get the generated customer code
                $get_code_sql = "SELECT customer_code FROM customers WHERE customer_id = ?";
                $code_stmt = $conn->prepare($get_code_sql);
                $code_stmt->bind_param("i", $customer_id);
                $code_stmt->execute();
                $customer_data = $code_stmt->get_result()->fetch_assoc();
                
                $success_message = "Customer registered successfully! Customer Code: " . $customer_data['customer_code'];
                
                // Clear form data after successful submission
                $_POST = array();
            } else {
                $error_message = "Error registering customer. Please try again.";
            }
        }
    }
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Register Customer - Laundry Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .form-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .form-subtitle {
            color: #64748b;
            margin-bottom: 2rem;
        }
        
        .form-label {
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .btn-primary {
            background: #3b82f6;
            border: 1px solid #3b82f6;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            border-color: #1d4ed8;
        }
        
        .btn-secondary {
            background: #6b7280;
            border: 1px solid #6b7280;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-block;
            transition: all 0.2s ease;
        }
        
        .btn-secondary:hover {
            background: #4b5563;
            border-color: #4b5563;
            color: white;
        }
        
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        
        .alert-success {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            color: #166534;
        }
        
        .alert-danger {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #991b1b;
        }
        
        .required {
            color: #ef4444;
        }
        
        .row {
            margin-left: -0.75rem;
            margin-right: -0.75rem;
        }
        
        .col-md-6 {
            padding-left: 0.75rem;
            padding-right: 0.75rem;
        }
        
        @media (min-width: 768px) {
            .col-md-6 {
                flex: 0 0 50%;
                max-width: 50%;
            }
        }
        
        .mb-3 {
            margin-bottom: 1rem;
        }
        
        .d-flex {
            display: flex;
        }
        
        .justify-content-between {
            justify-content: space-between;
        }
        
        .align-items-center {
            align-items: center;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div>
                            <h4 class="mb-0">Register New Customer</h4>
                            <p class="text-muted mb-0">Add a new customer to the system</p>
                        </div>
                        <a href="list_customers.php" class="btn-secondary">
                            <i class="ph-list me-2"></i>View All Customers
                        </a>
                    </div>

                    <!-- Registration Form -->
                    <div class="form-card">
                        <?php if ($success_message): ?>
                        <div class="alert alert-success">
                            <strong>Success!</strong> <?php echo $success_message; ?>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($error_message): ?>
                        <div class="alert alert-danger">
                            <strong>Error!</strong> <?php echo $error_message; ?>
                        </div>
                        <?php endif; ?>

                        <form method="POST" action="register_customer.php">
                            <div class="row">
                                <!-- Personal Information -->
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="first_name" class="form-label">
                                            First Name <span class="required">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="first_name" name="first_name" 
                                               value="<?php echo isset($_POST['first_name']) ? htmlspecialchars($_POST['first_name']) : ''; ?>" 
                                               required maxlength="50">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="last_name" class="form-label">
                                            Last Name <span class="required">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="last_name" name="last_name" 
                                               value="<?php echo isset($_POST['last_name']) ? htmlspecialchars($_POST['last_name']) : ''; ?>" 
                                               required maxlength="50">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="phone" class="form-label">
                                            Phone Number <span class="required">*</span>
                                        </label>
                                        <input type="tel" class="form-control" id="phone" name="phone" 
                                               value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>" 
                                               required maxlength="20" placeholder="e.g. +254712345678">
                                        <small class="text-muted">Phone number must be unique</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="email" class="form-label">Email Address</label>
                                        <input type="email" class="form-control" id="email" name="email" 
                                               value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" 
                                               maxlength="100" placeholder="customer@example.com">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="date_of_birth" class="form-label">Date of Birth</label>
                                        <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" 
                                               value="<?php echo isset($_POST['date_of_birth']) ? $_POST['date_of_birth'] : ''; ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="gender" class="form-label">Gender</label>
                                        <select class="form-control" id="gender" name="gender">
                                            <option value="">Select Gender</option>
                                            <option value="Male" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'Male') ? 'selected' : ''; ?>>Male</option>
                                            <option value="Female" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'Female') ? 'selected' : ''; ?>>Female</option>
                                            <option value="Other" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'Other') ? 'selected' : ''; ?>>Other</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="customer_type" class="form-label">Customer Type</label>
                                        <select class="form-control" id="customer_type" name="customer_type">
                                            <option value="Regular" <?php echo (!isset($_POST['customer_type']) || $_POST['customer_type'] == 'Regular') ? 'selected' : ''; ?>>Regular</option>
                                            <option value="VIP" <?php echo (isset($_POST['customer_type']) && $_POST['customer_type'] == 'VIP') ? 'selected' : ''; ?>>VIP</option>
                                            <option value="Corporate" <?php echo (isset($_POST['customer_type']) && $_POST['customer_type'] == 'Corporate') ? 'selected' : ''; ?>>Corporate</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="address" class="form-label">Address</label>
                                        <textarea class="form-control" id="address" name="address" rows="3" 
                                                  placeholder="Enter customer's address"><?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address']) : ''; ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="notes" class="form-label">Additional Notes</label>
                                        <textarea class="form-control" id="notes" name="notes" rows="3" 
                                                  placeholder="Any additional information about the customer"><?php echo isset($_POST['notes']) ? htmlspecialchars($_POST['notes']) : ''; ?></textarea>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between align-items-center">
                                <a href="list_customers.php" class="btn-secondary">
                                    <i class="ph-arrow-left me-2"></i>Cancel
                                </a>
                                <button type="submit" class="btn-primary">
                                    <i class="ph-user-plus me-2"></i>Register Customer
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Customer Information Help -->
                    <div class="form-card">
                        <h5 class="mb-3">Registration Guidelines</h5>
                        <div class="row">
                            <div class="col-md-4">
                                <h6 class="text-primary">Required Information</h6>
                                <ul class="list-unstyled">
                                    <li>• First Name</li>
                                    <li>• Last Name</li>
                                    <li>• Phone Number (must be unique)</li>
                                </ul>
                            </div>
                            <div class="col-md-4">
                                <h6 class="text-primary">Customer Types</h6>
                                <ul class="list-unstyled">
                                    <li>• <strong>Regular:</strong> Standard customers</li>
                                    <li>• <strong>VIP:</strong> Premium customers with special rates</li>
                                    <li>• <strong>Corporate:</strong> Business customers</li>
                                </ul>
                            </div>
                            <div class="col-md-4">
                                <h6 class="text-primary">System Features</h6>
                                <ul class="list-unstyled">
                                    <li>• Auto-generated customer code</li>
                                    <li>• Loyalty points tracking</li>
                                    <li>• Order history management</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        // Auto-format phone number
        document.getElementById('phone').addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '');
            if (value.startsWith('0')) {
                value = '254' + value.substring(1);
            }
            if (value.startsWith('254')) {
                e.target.value = '+' + value;
            }
        });

        // Form validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const firstName = document.getElementById('first_name').value.trim();
            const lastName = document.getElementById('last_name').value.trim();
            const phone = document.getElementById('phone').value.trim();
            
            if (!firstName || !lastName || !phone) {
                e.preventDefault();
                alert('Please fill in all required fields (First Name, Last Name, and Phone Number).');
                return false;
            }
            
            // Basic phone validation
            if (phone.length < 10) {
                e.preventDefault();
                alert('Please enter a valid phone number.');
                return false;
            }
        });

        // Clear success message after 5 seconds
        <?php if ($success_message): ?>
        setTimeout(function() {
            const alert = document.querySelector('.alert-success');
            if (alert) {
                alert.style.transition = 'opacity 0.5s';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 500);
            }
        }, 5000);
        <?php endif; ?>
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>