/home/awneajlw/.trash/new-order.php
<?php
/**
 * New Order Page - Create New Patient Order
 * This page allows users to create new orders for patients
 * Includes patient details, prescription information, and order details
 * Features: Form validation, database integration, auto-tracking ID generation
 */

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Include required files
require_once 'config/database.php';  // Database connection configuration
require_once 'includes/auth.php';    // Authentication functions

/**
 * Authentication Check
 * Redirect to welcome page if user is not logged in
 */
if (!isLoggedIn()) {
    header('Location: welcome.php');
    exit();
}

// Initialize variables for form handling
$success_message = '';   // Success message after form submission
$error_message = '';     // Error message for database issues
$field_errors = [];      // Array to store field-specific errors
$form_data = [];         // Array to store form data for repopulation

/**
 * Form Submission Handler
 * Process POST request when form is submitted
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $patient_name = trim($_POST['patient_name'] ?? '');
    $whatsapp_number = trim($_POST['whatsapp_number'] ?? '');
    $frame_detail = trim($_POST['frame_detail'] ?? '');
    $lens_type = trim($_POST['lens_type'] ?? '');
    $total_amount = trim($_POST['total_amount'] ?? '');
    $advance = trim($_POST['advance'] ?? '');
    $balance = trim($_POST['balance'] ?? '');
    $delivery_date = trim($_POST['delivery_date'] ?? '');
    
    // Prescription data
    $right_sph = trim($_POST['right_sph'] ?? '');
    $right_cyl = trim($_POST['right_cyl'] ?? '');
    $right_axis = trim($_POST['right_axis'] ?? '');
    $left_sph = trim($_POST['left_sph'] ?? '');
    $left_cyl = trim($_POST['left_cyl'] ?? '');
    $left_axis = trim($_POST['left_axis'] ?? '');
    $add_power = trim($_POST['add_power'] ?? '');
    
    $important_note = trim($_POST['important_note'] ?? '');
    
    // Store form data for repopulating
    // Fix delivery_date - convert empty string to NULL for database
    if (empty($delivery_date)) {
        $delivery_date = null;
    }
    
    $form_data = [
        'patient_name' => $patient_name,
        'whatsapp_number' => $whatsapp_number,
        'frame_detail' => $frame_detail,
        'lens_type' => $lens_type,
        'total_amount' => $total_amount,
        'advance' => $advance,
        'balance' => $balance,
        'delivery_date' => $delivery_date ?: '',
        'right_sph' => $right_sph,
        'right_cyl' => $right_cyl,
        'right_axis' => $right_axis,
        'left_sph' => $left_sph,
        'left_cyl' => $left_cyl,
        'left_axis' => $left_axis,
        'add_power' => $add_power,
        'important_note' => $important_note
    ];
    
    // Basic validation - only check required fields
    $validation_errors = [];
    
    if (empty($patient_name)) {
        $validation_errors['patient_name'] = 'Patient name is required';
    }
    
    if (empty($whatsapp_number)) {
        $validation_errors['whatsapp_number'] = 'WhatsApp number is required';
    }
    
    if (empty($total_amount)) {
        $validation_errors['total_amount'] = 'Total amount is required';
    } elseif (!is_numeric($total_amount) || $total_amount <= 0) {
        $validation_errors['total_amount'] = 'Please enter a valid total amount';
    }
    
    if (empty($validation_errors)) {
        try {
            $database = new Database();
            $db = $database->getConnection();
            
            // Create orders table if it doesn't exist
            $create_table_sql = "CREATE TABLE IF NOT EXISTS orders (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                tracking_id VARCHAR(50) DEFAULT NULL,
                patient_name VARCHAR(255) NOT NULL,
                whatsapp_number VARCHAR(20) NOT NULL,
                frame_detail VARCHAR(255) DEFAULT NULL,
                lens_type VARCHAR(255) DEFAULT NULL,
                total_amount DECIMAL(10,2) NOT NULL,
                advance DECIMAL(10,2) DEFAULT 0,
                balance DECIMAL(10,2) DEFAULT 0,
                delivery_date DATE DEFAULT NULL,
                right_sph VARCHAR(10) DEFAULT NULL,
                right_cyl VARCHAR(10) DEFAULT NULL,
                right_axis VARCHAR(10) DEFAULT NULL,
                left_sph VARCHAR(10) DEFAULT NULL,
                left_cyl VARCHAR(10) DEFAULT NULL,
                left_axis VARCHAR(10) DEFAULT NULL,
                add_power VARCHAR(10) DEFAULT NULL,
                important_note TEXT DEFAULT NULL,
                description TEXT DEFAULT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_user_id (user_id),
                INDEX idx_tracking_id (tracking_id),
                INDEX idx_patient_name (patient_name),
                INDEX idx_created_at (created_at)
            )";
            
            $db->exec($create_table_sql);
            
            $user_id = $_SESSION['user_id'];
            
            // Calculate balance if not provided
            if (empty($balance) && !empty($total_amount) && !empty($advance)) {
                $balance = $total_amount - $advance;
            }
            
            // Get next order number for tracking ID
            $count_query = "SELECT COUNT(*) as count FROM orders WHERE user_id = ?";
            $count_stmt = $db->prepare($count_query);
            $count_stmt->execute([$user_id]);
            $count_result = $count_stmt->fetch(PDO::FETCH_ASSOC);
            $next_order_number = ($count_result['count'] ?? 0) + 1;
            
            // Generate tracking ID
            $tracking_id = 'T' . str_pad($next_order_number, 4, '0', STR_PAD_LEFT);
            
            // Insert new order
            $insert_query = "INSERT INTO orders (
                user_id, tracking_id, patient_name, whatsapp_number, frame_detail, lens_type, 
                total_amount, advance, balance, delivery_date, right_sph, right_cyl, 
                right_axis, left_sph, left_cyl, left_axis, add_power, important_note, 
                created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
            
            $stmt = $db->prepare($insert_query);
            $stmt->execute([
                $user_id, $tracking_id, $patient_name, $whatsapp_number, $frame_detail, $lens_type,
                $total_amount, $advance, $balance, $delivery_date, $right_sph, $right_cyl,
                $right_axis, $left_sph, $left_cyl, $left_axis, $add_power, $important_note
            ]);
            
            $order_id = $db->lastInsertId();
            
            // Redirect to slip page
            header('Location: order-slip.php?id=' . $order_id);
            exit();
            
        } catch (Exception $e) {
            $error_message = 'Database error: ' . $e->getMessage();
        }
    } else {
        $field_errors = $validation_errors;
        $error_message = 'Please correct the errors below and try again.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Order - OPTI SLIP</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #1e40af 0%, #7c3aed 100%);
            min-height: 100vh;
            padding: 0;
            margin: 0;
        }
        
        .container {
            max-width: 100%;
            margin: 0;
            padding: 0;
        }
        
        .main-content {
            background: white;
            border-radius: 0;
            padding: 30px;
            box-shadow: none;
            min-height: 100vh;
            max-width: 100%;
            margin: 0;
        }
        
        .page-header {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }
        
        .back-btn {
            background: #10b981;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: #059669;
            transform: translateY(-2px);
        }
        
        .page-title {
            color: #6b7280;
            font-size: 24px;
            font-weight: 500;
        }
        
        .opti-slip-header {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 30px;
        }
        
        .opti-logo-container {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .opti-logo {
            width: 50px;
            height: 50px;
            background: white;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }
        
        .opti-logo.qr {
            background: #f3f4f6;
        }
        
        .opti-logo.doc {
            background: #e5e7eb;
        }
        
        .glasses-icon {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #10b981;
            font-size: 20px;
            z-index: 2;
        }
        
        .qr-pattern {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: repeating-linear-gradient(
                0deg,
                #d1d5db 0px,
                #d1d5db 2px,
                transparent 2px,
                transparent 4px
            ),
            repeating-linear-gradient(
                90deg,
                #d1d5db 0px,
                #d1d5db 2px,
                transparent 2px,
                transparent 4px
            );
        }
        
        .doc-lines {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 30px;
            height: 20px;
            border-top: 2px solid #9ca3af;
            border-bottom: 2px solid #9ca3af;
        }
        
        .opti-title {
            color: #10b981;
            font-size: 24px;
            font-weight: bold;
            margin: 0;
        }
        
        .order-form-container {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: 2px solid #e5e7eb;
            max-width: 800px;
            margin: 0 auto;
        }
        
        .form-section {
            margin-bottom: 30px;
        }
        
        .section-title {
            color: #1f2937;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .form-group.full-width {
            grid-column: 1 / -1;
        }
        
        .form-label {
            color: #374151;
            font-weight: 600;
            font-size: 14px;
        }
        
        .form-input {
            padding: 12px 15px;
            border: 2px dashed #3b82f6;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #f9fafb;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #10b981;
            border-style: solid;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
            background: white;
        }
        
        .form-input.error {
            border-color: #ef4444;
            border-style: solid;
            background-color: #fef2f2;
        }
        
        .form-input.error:focus {
            border-color: #dc2626;
            box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
        }
        
        .error-message {
            color: #ef4444;
            font-size: 12px;
            margin-top: 5px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .error-message i {
            font-size: 10px;
        }
        
        .form-group.has-error .form-label {
            color: #ef4444;
        }
        
        .prescription-input.error {
            border-color: #ef4444;
            background-color: #fef2f2;
        }
        
        .prescription-input.error:focus {
            border-color: #dc2626;
            box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
        }
        
        .prescription-section {
            background: #f9fafb;
            padding: 25px;
            border-radius: 12px;
            border: 2px solid #e5e7eb;
        }
        
        .eye-section {
            margin-bottom: 25px;
        }
        
        .eye-title {
            color: #1f2937;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
        }
        
        .prescription-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;
            align-items: end;
        }
        
        .prescription-input-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .prescription-label {
            color: #374151;
            font-weight: 600;
            font-size: 14px;
        }
        
        .prescription-input-container {
            position: relative;
            display: flex;
            align-items: center;
        }
        
        .prescription-input {
            width: 100%;
            padding: 10px 60px 10px 60px;
            border: 2px solid #e5e7eb;
            border-radius: 6px;
            font-size: 16px;
            text-align: center;
            background: white;
            transition: all 0.3s ease;
        }
        
        .prescription-input:focus {
            outline: none;
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
        }
        
        .input-controls {
            position: absolute;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            top: 50%;
            transform: translateY(-50%);
            padding: 0 5px;
            pointer-events: none;
        }
        
        .control-btn {
            background: #10b981;
            color: white;
            border: none;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            pointer-events: auto;
        }
        
        .control-btn:hover {
            background: #059669;
            transform: scale(1.1);
        }
        
        .dropdown-btn {
            background: #6b7280;
            color: white;
            border: none;
            width: 20px;
            height: 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            pointer-events: auto;
        }
        
        .left-controls {
            display: flex;
            gap: 3px;
        }
        
        .right-controls {
            display: flex;
            gap: 3px;
        }
        
        .important-note-section {
            margin-top: 30px;
        }
        
        .textarea {
            padding: 15px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 16px;
            resize: vertical;
            min-height: 100px;
            transition: all 0.3s ease;
            background: #f9fafb;
        }
        
        .textarea:focus {
            outline: none;
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
            background: white;
        }
        
        .generate-slip-btn {
            background: #10b981;
            color: white;
            border: none;
            padding: 15px 40px;
            border-radius: 12px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 30px auto;
            display: block;
        }
        
        .generate-slip-btn:hover {
            background: #059669;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(16, 185, 129, 0.3);
        }
        
        .alert {
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            border: none;
        }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        @media (max-width: 768px) {
            .main-content {
                padding: 15px;
            }
            
            .order-form-container {
                padding: 25px;
                margin: 0;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .prescription-grid {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .eye-section {
                margin-bottom: 20px;
            }
            
            .prescription-input {
                padding: 12px 50px 12px 50px;
                font-size: 14px;
            }
            
            .control-btn {
                width: 18px;
                height: 18px;
                font-size: 9px;
            }
            
            .dropdown-btn {
                width: 18px;
                height: 18px;
                font-size: 7px;
            }
        }
        
        @media (max-width: 480px) {
            .main-content {
                padding: 10px;
            }
            
            .order-form-container {
                padding: 20px;
                border-radius: 15px;
            }
            
            .page-title {
                font-size: 20px;
            }
            
            .opti-title {
                font-size: 20px;
            }
            
            .opti-logo {
                width: 40px;
                height: 40px;
            }
            
            .glasses-icon {
                font-size: 16px;
            }
            
            .prescription-input {
                padding: 10px 45px 10px 45px;
                font-size: 13px;
            }
            
            .control-btn {
                width: 16px;
                height: 16px;
                font-size: 8px;
            }
            
            .dropdown-btn {
                width: 16px;
                height: 16px;
                font-size: 6px;
            }
            
            .left-controls,
            .right-controls {
                gap: 2px;
            }
            
            .section-title {
                font-size: 18px;
            }
            
            .eye-title {
                font-size: 16px;
            }

        }

        .important-note-section {
    width: 100%;
}

.important-note-section .textarea {
    width: 100%;
    min-height: 120px; /* optional */
    box-sizing: border-box;
}

    </style>
</head>
<body>
    <div class="container">
        <div class="main-content">
            <!-- Page Header -->
            <div class="page-header">
                <button class="back-btn" onclick="goBack()">
                    <i class="fas fa-arrow-left"></i>
                    Back
                </button>
                <h1 class="page-title">new order</h1>
            </div>
            
            <!-- Opti Slip Header -->
            <div class="opti-slip-header">
                <div class="opti-logo-container">
                    <div class="opti-logo qr">
                        <div class="qr-pattern"></div>
                        <i class="fas fa-glasses glasses-icon"></i>
                    </div>
                    <div class="opti-logo doc">
                        <div class="doc-lines"></div>
                        <i class="fas fa-glasses glasses-icon"></i>
                    </div>
                </div>
                <h2 class="opti-title">OPTI SLIP</h2>
            </div>
            
            <!-- Order Form -->
            <div class="order-form-container">
                <?php if ($success_message): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <?php echo htmlspecialchars($success_message); ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        <?php echo htmlspecialchars($error_message); ?>
                    </div>
                <?php endif; ?>
                
                <form method="POST" id="orderForm">
                    <!-- Patient and Order Details -->
                    <div class="form-section">
                        <h3 class="section-title">Patient & Order Details</h3>
                        <div class="form-grid">
                            <div class="form-group <?php echo isset($field_errors['patient_name']) ? 'has-error' : ''; ?>">
                                <label class="form-label">Patient Name</label>
                                <input type="text" name="patient_name" class="form-input <?php echo isset($field_errors['patient_name']) ? 'error' : ''; ?>" 
                                       placeholder="XXXXXXXXXX" required 
                                       value="<?php echo htmlspecialchars($form_data['patient_name'] ?? ''); ?>">
                                <?php if (isset($field_errors['patient_name'])): ?>
                                    <div class="error-message">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        <?php echo htmlspecialchars($field_errors['patient_name']); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="form-group <?php echo isset($field_errors['whatsapp_number']) ? 'has-error' : ''; ?>">
                                <label class="form-label">WhatsApp Number</label>
                                <input type="tel" name="whatsapp_number" class="form-input <?php echo isset($field_errors['whatsapp_number']) ? 'error' : ''; ?>" 
                                       placeholder="XXXXXXXXXX" required 
                                       value="<?php echo htmlspecialchars($form_data['whatsapp_number'] ?? ''); ?>">
                                <?php if (isset($field_errors['whatsapp_number'])): ?>
                                    <div class="error-message">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        <?php echo htmlspecialchars($field_errors['whatsapp_number']); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Frame Detail</label>
                                <input type="text" name="frame_detail" class="form-input" 
                                       placeholder="XXXXXXXXXX"
                                       value="<?php echo htmlspecialchars($form_data['frame_detail'] ?? ''); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Lens Type</label>
                                <input type="text" name="lens_type" class="form-input" 
                                       placeholder="XXXXXXXXXX"
                                       value="<?php echo htmlspecialchars($form_data['lens_type'] ?? ''); ?>">
                            </div>
                            
                            <div class="form-group <?php echo isset($field_errors['total_amount']) ? 'has-error' : ''; ?>">
                                <label class="form-label">Total Amount</label>
                                <input type="number" name="total_amount" class="form-input <?php echo isset($field_errors['total_amount']) ? 'error' : ''; ?>" 
                                       placeholder="0" required 
                                       value="<?php echo htmlspecialchars($form_data['total_amount'] ?? ''); ?>"
                                       onchange="calculateBalance()">
                                <?php if (isset($field_errors['total_amount'])): ?>
                                    <div class="error-message">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        <?php echo htmlspecialchars($field_errors['total_amount']); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Advance</label>
                                <input type="number" name="advance" class="form-input" 
                                       placeholder="0" onchange="calculateBalance()"
                                       value="<?php echo htmlspecialchars($form_data['advance'] ?? ''); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Balance</label>
                                <input type="number" name="balance" class="form-input" 
                                       placeholder="0" readonly
                                       value="<?php echo htmlspecialchars($form_data['balance'] ?? ''); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Delivery Date</label>
                                <input type="date" name="delivery_date" class="form-input"
                                       value="<?php echo htmlspecialchars($form_data['delivery_date'] ?? ''); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Prescription Details -->
                    <div class="form-section">
                        <h3 class="section-title">Prescription Details</h3>
                        <div class="prescription-section">
                            <!-- Right Eye -->
                            <div class="eye-section">
                                <h4 class="eye-title">Right Eye:</h4>
                                <div class="prescription-grid">
                                    <div class="prescription-input-group <?php echo isset($field_errors['right_sph']) ? 'has-error' : ''; ?>">
                                        <label class="prescription-label">SPH (Sphere)</label>
                                        <div class="prescription-input-container">
                                            <input type="text" name="right_sph" class="prescription-input <?php echo isset($field_errors['right_sph']) ? 'error' : ''; ?>" 
                                                   value="<?php echo htmlspecialchars($form_data['right_sph'] ?? '0.00'); ?>" id="rightSph">
                                            <div class="input-controls">
                                                <div class="left-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('rightSph', -0.25)">-</button>
                                                    <button type="button" class="dropdown-btn" onclick="showDropdown('rightSph')">▼</button>
                                                </div>
                                                <div class="right-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('rightSph', 0.25)">+</button>
                                                    <!-- <button type="button" class="control-btn" onclick="adjustValue('rightSph', 0.25)">+</button> -->
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="prescription-input-group">
                                        <label class="prescription-label">CYL (Cylinder)</label>
                                        <div class="prescription-input-container">
                                            <input type="text" name="right_cyl" class="prescription-input" 
                                                   value="1.00" id="rightCyl">
                                            <div class="input-controls">
                                                <div class="left-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('rightCyl', -0.25)">-</button>
                                                    <button type="button" class="dropdown-btn" onclick="showDropdown('rightCyl')">▼</button>
                                                </div>
                                                <div class="right-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('rightCyl', 0.25)">+</button>
                                                    <!-- <button type="button" class="control-btn" onclick="adjustValue('rightCyl', 0.25)">+</button> -->
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="prescription-input-group">
                                        <label class="prescription-label">AXIS</label>
                                        <div class="prescription-input-container">
                                            <input type="text" name="right_axis" class="prescription-input" 
                                                   value="0" id="rightAxis">
                                            <div class="input-controls">
                                                <div class="left-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('rightAxis', -1)">-</button>
                                                    <button type="button" class="dropdown-btn" onclick="showDropdown('rightAxis')">▼</button>
                                                </div>
                                                <div class="right-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('rightAxis', 1)">+</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Left Eye -->
                            <div class="eye-section">
                                <h4 class="eye-title">Left Eye:</h4>
                                <div class="prescription-grid">
                                    <div class="prescription-input-group">
                                        <label class="prescription-label">SPH (Sphere)</label>
                                        <div class="prescription-input-container">
                                            <input type="text" name="left_sph" class="prescription-input" 
                                                   value="0.25" id="leftSph">
                                            <div class="input-controls">
                                                <div class="left-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('leftSph', -0.25)">-</button>
                                                    <button type="button" class="dropdown-btn" onclick="showDropdown('leftSph')">▼</button>
                                                </div>
                                                <div class="right-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('leftSph', 0.25)">+</button>
                                                    <!-- <button type="button" class="control-btn" onclick="adjustValue('leftSph', 0.25)">+</button> -->
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="prescription-input-group">
                                        <label class="prescription-label">CYL (Cylinder)</label>
                                        <div class="prescription-input-container">
                                            <input type="text" name="left_cyl" class="prescription-input" 
                                                   value="0.75" id="leftCyl">
                                            <div class="input-controls">
                                                <div class="left-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('leftCyl', -0.25)">-</button>
                                                    <button type="button" class="dropdown-btn" onclick="showDropdown('leftCyl')">▼</button>
                                                </div>
                                                <div class="right-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('leftCyl', 0.25)">+</button>
                                                    <!-- <button type="button" class="control-btn" onclick="adjustValue('leftCyl', 0.25)">+</button> -->
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="prescription-input-group">
                                        <label class="prescription-label">AXIS</label>
                                        <div class="prescription-input-container">
                                            <input type="text" name="left_axis" class="prescription-input" 
                                                   value="0" id="leftAxis">
                                            <div class="input-controls">
                                                <div class="left-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('leftAxis', -1)">-</button>
                                                    <button type="button" class="dropdown-btn" onclick="showDropdown('leftAxis')">▼</button>
                                                </div>
                                                <div class="right-controls">
                                                    <button type="button" class="control-btn" onclick="adjustValue('leftAxis', 1)">+</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- ADD Power -->
                            <div class="eye-section">
                                <div class="form-group">
                                    <label class="form-label">ADD (Addition)</label>
                                    <input type="text" name="add_power" class="form-input" 
                                           placeholder="XXXXXXXXXX">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Important Note -->
                    <div class="form-section important-note-section">
                        <h3 class="section-title">Important Note</h3>
                        <textarea name="important_note" class="textarea" 
                                  placeholder="Type Here...."></textarea>
                    </div>
                    
                    <!-- Generate Slip Button -->
                    <button type="submit" class="generate-slip-btn">
                        <i class="fas fa-file-alt"></i>
                        Generate Slip
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function goBack() {
            window.history.back();
        }
        
        function adjustValue(inputId, change) {
            const input = document.getElementById(inputId);
            let currentValue = parseFloat(input.value) || 0;
            
            // Round to 0.25 increments for SPH and CYL
            if (inputId.includes('Sph') || inputId.includes('Cyl')) {
                currentValue = Math.round(currentValue * 4) / 4;
                newValue = currentValue + change;
                newValue = Math.round(newValue * 4) / 4;
            } else {
                // For AXIS, round to whole numbers
                newValue = Math.round(currentValue + change);
                if (newValue < 0) newValue = 0;
                if (newValue > 180) newValue = 180;
            }
            
            input.value = newValue.toFixed(2);
        }
        
        function calculateBalance() {
            const totalAmount = parseFloat(document.querySelector('input[name="total_amount"]').value) || 0;
            const advance = parseFloat(document.querySelector('input[name="advance"]').value) || 0;
            const balance = totalAmount - advance;
            
            document.querySelector('input[name="balance"]').value = Math.max(0, balance).toFixed(2);
        }
        
        function showDropdown(inputId) {
            // This would show a dropdown with common values
            // For now, we'll just focus the input
            document.getElementById(inputId).focus();
        }
        
        // Auto-calculate balance when total amount changes
        document.querySelector('input[name="total_amount"]').addEventListener('input', calculateBalance);
        
        // Form validation and error handling
        document.getElementById('orderForm').addEventListener('submit', function(e) {
            const requiredFields = this.querySelectorAll('input[required]');
            let isValid = true;
            let firstErrorField = null;
            
            // Clear previous error styles
            document.querySelectorAll('.form-input.error, .prescription-input.error').forEach(field => {
                field.classList.remove('error');
            });
            document.querySelectorAll('.error-message').forEach(msg => {
                msg.remove();
            });
            document.querySelectorAll('.form-group.has-error').forEach(group => {
                group.classList.remove('has-error');
            });
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('error');
                    field.closest('.form-group').classList.add('has-error');
                    
                    // Add error message
                    const errorMsg = document.createElement('div');
                    errorMsg.className = 'error-message';
                    errorMsg.innerHTML = '<i class="fas fa-exclamation-triangle"></i>This field is required';
                    field.closest('.form-group').appendChild(errorMsg);
                    
                    if (!firstErrorField) {
                        firstErrorField = field;
                    }
                    isValid = false;
                }
            });
            
            // Validate only total amount field
            const totalAmountField = document.querySelector('input[name="total_amount"]');
            if (totalAmountField && totalAmountField.value && (!isNumeric(totalAmountField.value) || parseFloat(totalAmountField.value) <= 0)) {
                totalAmountField.classList.add('error');
                totalAmountField.closest('.form-group').classList.add('has-error');
                
                const errorMsg = document.createElement('div');
                errorMsg.className = 'error-message';
                errorMsg.innerHTML = '<i class="fas fa-exclamation-triangle"></i>Please enter a valid total amount';
                totalAmountField.closest('.form-group').appendChild(errorMsg);
                
                if (!firstErrorField) {
                    firstErrorField = totalAmountField;
                }
                isValid = false;
            }
            
            if (!isValid) {
                e.preventDefault();
                if (firstErrorField) {
                    firstErrorField.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    firstErrorField.focus();
                }
                return false;
            }
        });
        
        // Helper function to check if value is numeric
        function isNumeric(value) {
            return !isNaN(parseFloat(value)) && isFinite(value);
        }
        
        // Auto-focus first input
        document.addEventListener('DOMContentLoaded', function() {
            const firstInput = document.querySelector('input[name="patient_name"]');
            if (firstInput) {
                firstInput.focus();
            }
        });
    </script>
</body>
</html>