<?php
/**
 * Test Script for Shipment Status Update Feature
 * Run this to verify all API endpoints are working correctly
 */

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
    <title>Shipment Status Update - API Test</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 1000px; margin: 0 auto; }
        .test-section { background: white; padding: 20px; margin-bottom: 20px; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        .test-title { font-size: 18px; font-weight: bold; color: #333; margin-bottom: 15px; border-bottom: 2px solid #2196F3; padding-bottom: 10px; }
        .test-case { margin: 15px 0; padding: 10px; background: #f9f9f9; border-left: 3px solid #2196F3; }
        .test-btn { padding: 8px 15px; background: #2196F3; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px; }
        .test-btn:hover { background: #1976D2; }
        .result { margin-top: 10px; padding: 10px; border-radius: 4px; font-size: 12px; }
        .result.success { background: #e8f5e9; color: #2e7d32; border-left: 3px solid #4caf50; }
        .result.error { background: #ffebee; color: #c62828; border-left: 3px solid #f44336; }
        .result.loading { background: #e3f2fd; color: #1976d2; border-left: 3px solid #2196f3; }
        .code { background: #f0f0f0; padding: 10px; border-radius: 4px; font-family: 'Courier New'; font-size: 11px; overflow-x: auto; margin-top: 5px; }
        .status-ok { color: #4caf50; font-weight: bold; }
        .status-fail { color: #f44336; font-weight: bold; }
        .status-pending { color: #ff9800; font-weight: bold; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 Shipment Status Update - Feature Test</h1>
        
        <div class="test-section">
            <div class="test-title">1. API Endpoint Tests</div>
            
            <div class="test-case">
                <strong>Test: Get All Shipments</strong>
                <button class="test-btn" onclick="testGetShipments()">Test API</button>
                <div id="result-shipments" class="result loading" style="display:none;"></div>
            </div>

            <div class="test-case">
                <strong>Test: Get Branches (for filter)</strong>
                <button class="test-btn" onclick="testGetBranches()">Test API</button>
                <div id="result-branches" class="result loading" style="display:none;"></div>
            </div>

            <div class="test-case">
                <strong>Test: Get Single Booking</strong>
                <div>
                    <input type="number" id="bookingId" placeholder="Enter Booking ID (e.g., 1)">
                    <button class="test-btn" onclick="testGetBooking()">Test API</button>
                </div>
                <div id="result-booking" class="result loading" style="display:none;"></div>
            </div>

            <div class="test-case">
                <strong>Test: Get Tracking History</strong>
                <div>
                    <input type="number" id="trackingBookingId" placeholder="Enter Booking ID (e.g., 1)">
                    <button class="test-btn" onclick="testGetTracking()">Test API</button>
                </div>
                <div id="result-tracking" class="result loading" style="display:none;"></div>
            </div>

            <div class="test-case">
                <strong>Test: Create Tracking Record (Dry Run)</strong>
                <div style="margin-bottom: 10px;">
                    <input type="number" id="createBookingId" placeholder="Booking ID" style="width: 150px;">
                    <input type="text" id="createStatus" placeholder="Status (e.g., In Transit)" style="width: 150px;">
                    <input type="date" id="createDate" style="width: 150px;">
                    <input type="text" id="createLocation" placeholder="Location" style="width: 150px;">
                </div>
                <button class="test-btn" onclick="testCreateTracking()">Test API</button>
                <div id="result-create" class="result loading" style="display:none;"></div>
            </div>
        </div>

        <div class="test-section">
            <div class="test-title">2. Database Schema Verification</div>
            
            <div class="test-case">
                <strong>Check Table Structure</strong>
                <button class="test-btn" onclick="testDatabaseSchema()">Check Schema</button>
                <div id="result-schema" class="result loading" style="display:none;"></div>
            </div>
        </div>

        <div class="test-section">
            <div class="test-title">3. Page Load Test</div>
            
            <div class="test-case">
                <strong>Load shipment-status-update.php</strong>
                <button class="test-btn" onclick="testPageLoad()">Load Page</button>
                <div id="result-pageload" class="result loading" style="display:none;"></div>
            </div>
        </div>

        <div class="test-section">
            <div class="test-title">Test Summary</div>
            <div id="summary" style="padding: 10px;">
                <p>Click the test buttons above to verify each component.</p>
                <p><span class="status-ok">✓ Success</span> - API/Feature working correctly</p>
                <p><span class="status-fail">✗ Error</span> - Issue detected, check response</p>
                <p><span class="status-pending">⏳ Loading</span> - Test in progress</p>
            </div>
        </div>
    </div>

    <script src="assets/plugins/jquery/jquery.min.js"></script>
    <script>
        function showResult(elementId, success, message, details = '') {
            const $elem = $('#' + elementId);
            $elem.removeClass('loading success error').addClass(success ? 'success' : 'error');
            let html = (success ? '✓ ' : '✗ ') + message;
            if (details) {
                html += '<div class="code">' + escapeHtml(details) + '</div>';
            }
            $elem.html(html).show();
        }

        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, m => map[m]);
        }

        function testGetShipments() {
            $('#result-shipments').addClass('loading').html('Loading...').show();
            $.ajax({
                url: 'api/shipment/read.php?length=5',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.data && response.data.length > 0) {
                        showResult('result-shipments', true, 
                            'Retrieved ' + response.data.length + ' shipments',
                            'Sample: ' + JSON.stringify(response.data[0], null, 2)
                        );
                    } else {
                        showResult('result-shipments', false, 'No shipments in database');
                    }
                },
                error: function(xhr) {
                    showResult('result-shipments', false, 'API Error: ' + xhr.status, xhr.responseText);
                }
            });
        }

        function testGetBranches() {
            $('#result-branches').addClass('loading').html('Loading...').show();
            $.ajax({
                url: 'api/branch/read.php?length=-1',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.data && response.data.length > 0) {
                        showResult('result-branches', true, 
                            'Retrieved ' + response.data.length + ' branches',
                            'Branches: ' + response.data.map(b => b.branch_name).join(', ')
                        );
                    } else {
                        showResult('result-branches', false, 'No branches found');
                    }
                },
                error: function(xhr) {
                    showResult('result-branches', false, 'API Error: ' + xhr.status, xhr.responseText);
                }
            });
        }

        function testGetBooking() {
            const bookingId = $('#bookingId').val();
            if (!bookingId) {
                alert('Please enter a Booking ID');
                return;
            }
            $('#result-booking').addClass('loading').html('Loading...').show();
            $.ajax({
                url: 'api/booking/readone.php?id=' + bookingId,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        showResult('result-booking', true, 
                            'Booking #' + bookingId + ' loaded',
                            'Booking: ' + JSON.stringify(response.data, null, 2).substring(0, 500)
                        );
                    } else {
                        showResult('result-booking', false, response.message || 'Error loading booking');
                    }
                },
                error: function(xhr) {
                    showResult('result-booking', false, 'API Error: ' + xhr.status, xhr.responseText);
                }
            });
        }

        function testGetTracking() {
            const bookingId = $('#trackingBookingId').val();
            if (!bookingId) {
                alert('Please enter a Booking ID');
                return;
            }
            $('#result-tracking').addClass('loading').html('Loading...').show();
            $.ajax({
                url: 'api/tracking/read.php?id=' + bookingId,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        const scansCount = response.scans_count || 0;
                        showResult('result-tracking', true, 
                            'Tracking history loaded: ' + scansCount + ' scans',
                            'Current Status: ' + response.current_status + '\nScans: ' + JSON.stringify(response.data?.Scans?.[0], null, 2)
                        );
                    } else {
                        showResult('result-tracking', false, response.message || 'Error loading tracking');
                    }
                },
                error: function(xhr) {
                    showResult('result-tracking', false, 'API Error: ' + xhr.status, xhr.responseText);
                }
            });
        }

        function testCreateTracking() {
            const bookingId = $('#createBookingId').val();
            const status = $('#createStatus').val();
            const date = $('#createDate').val();
            const location = $('#createLocation').val();

            if (!bookingId || !status || !date) {
                alert('Please fill in Booking ID, Status, and Date');
                return;
            }

            $('#result-create').addClass('loading').html('Sending request...').show();
            const formData = {
                booking_id: bookingId,
                status: status,
                status_date: date + 'T12:00',
                location: location || 'Not specified',
                remarks: 'Test update from verification script'
            };

            $.ajax({
                url: 'api/tracking/create.php',
                method: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        showResult('result-create', true,
                            'Tracking record created successfully (ID: ' + response.tracking_id + ')',
                            'Response: ' + JSON.stringify(response, null, 2)
                        );
                    } else {
                        showResult('result-create', false, response.message || 'Error creating tracking');
                    }
                },
                error: function(xhr) {
                    showResult('result-create', false, 'API Error: ' + xhr.status, xhr.responseText);
                }
            });
        }

        function testDatabaseSchema() {
            $('#result-schema').addClass('loading').html('Checking schema...').show();
            // This would require a backend script to check schema
            // For now, show expected schema
            const schema = `Expected Database Schema:

tbl_bookings:
- id (INT PK)
- waybill_no (VARCHAR)
- booking_ref_id (VARCHAR)
- consignee_name (VARCHAR)
- consignor_name (VARCHAR)
- last_status (VARCHAR)
- courier_id (INT FK)
- created_at (DATETIME)
- updated_at (DATETIME)

tbl_tracking:
- id (INT PK)
- booking_id (INT FK)
- scan_type (VARCHAR)
- scan_location (VARCHAR)
- scan_datetime (DATETIME)
- status_code (VARCHAR)
- remarks (TEXT)
- created_by (INT)
- created_at (DATETIME)

Verify these fields exist in your database.`;
            showResult('result-schema', true, 'Database schema guide', schema);
        }

        function testPageLoad() {
            $('#result-pageload').addClass('loading').html('Loading page...').show();
            $.ajax({
                url: 'shipment-status-update.php',
                method: 'GET',
                timeout: 5000,
                success: function() {
                    showResult('result-pageload', true, 
                        'Page loads successfully',
                        'Page: shipment-status-update.php (200 OK)'
                    );
                },
                error: function(xhr) {
                    showResult('result-pageload', false, 
                        'Page load error: ' + xhr.status,
                        xhr.statusText
                    );
                }
            });
        }

        // Set default date to today
        document.getElementById('createDate').valueAsDate = new Date();
    </script>
</body>
</html>
