<?php
/**
 * DIAGNOSTIC TOOL - Production Readiness Check
 * Run this to identify any setup issues
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<!DOCTYPE html>
<html><head><meta charset='UTF-8'><title>System Diagnostic</title>
<style>
body { font-family: Arial; background: #f5f5f5; padding: 40px; }
.container { max-width: 900px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
h1 { color: #667eea; margin-bottom: 30px; }
.section { margin-bottom: 30px; padding: 20px; background: #f9f9f9; border-left: 4px solid #667eea; border-radius: 4px; }
.section h2 { margin-top: 0; color: #333; font-size: 18px; }
.result { padding: 10px; margin: 10px 0; border-radius: 4px; }
.pass { background: #d4edda; color: #155724; border-left: 4px solid #28a745; }
.fail { background: #f8d7da; color: #721c24; border-left: 4px solid #dc3545; }
.warn { background: #fff3cd; color: #856404; border-left: 4px solid #ffc107; }
.code { background: #f0f0f0; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; margin: 10px 0; overflow-x: auto; }
</style></head><body>
<div class='container'>
<h1>🔍 System Diagnostic Report</h1>";

// Check 1: config.php exists
echo "<div class='section'><h2>1. Configuration File</h2>";
if (file_exists('config.php')) {
    echo "<div class='result pass'>✓ config.php exists</div>";

    // Try to load config
    try {
        require 'config.php';
        echo "<div class='result pass'>✓ config.php loaded successfully</div>";
    } catch (Exception $e) {
        echo "<div class='result fail'>✗ Error loading config.php: " . $e->getMessage() . "</div>";
    }
} else {
    echo "<div class='result fail'>✗ config.php NOT FOUND</div>";
    echo "<div class='warn'>→ This file should be created during setup wizard Step 5</div>";
}
echo "</div>";

// Check 2: Database Connection
echo "<div class='section'><h2>2. Database Connection</h2>";
if (isset($pdo)) {
    try {
        $test = $pdo->query("SELECT 1");
        echo "<div class='result pass'>✓ Database connection successful</div>";
        echo "<div class='result pass'>✓ Server: " . DB_HOST . "</div>";
        echo "<div class='result pass'>✓ Database: " . DB_NAME . "</div>";
        echo "<div class='result pass'>✓ User: " . DB_USER . "</div>";
    } catch (Exception $e) {
        echo "<div class='result fail'>✗ Database connection failed</div>";
        echo "<div class='code'>Error: " . $e->getMessage() . "</div>";
    }
} else {
    echo "<div class='result fail'>✗ PDO object not initialized</div>";
    echo "<div class='warn'>→ Check that config.php creates the \$pdo connection</div>";
}
echo "</div>";

// Check 3: Database Tables
echo "<div class='section'><h2>3. Database Schema</h2>";
if (isset($pdo)) {
    try {
        $tables = ['users', 'documents', 'signatures', 'sales', 'customers'];
        foreach ($tables as $table) {
            $result = $pdo->query("SHOW TABLES LIKE '$table'");
            if ($result->rowCount() > 0) {
                echo "<div class='result pass'>✓ Table '$table' exists</div>";
            } else {
                echo "<div class='result fail'>✗ Table '$table' NOT FOUND</div>";
            }
        }
    } catch (Exception $e) {
        echo "<div class='result fail'>✗ Error checking tables: " . $e->getMessage() . "</div>";
    }
} else {
    echo "<div class='result fail'>✗ Cannot check tables - database not connected</div>";
}
echo "</div>";

// Check 4: Users in Database
echo "<div class='section'><h2>4. User Accounts</h2>";
if (isset($pdo)) {
    try {
        $result = $pdo->query("SELECT COUNT(*) as count FROM users");
        $row = $result->fetch();
        $count = $row['count'] ?? 0;

        if ($count > 0) {
            echo "<div class='result pass'>✓ Found " . $count . " user account(s)</div>";

            // List users
            $users = $pdo->query("SELECT id, username, email, role, created_at FROM users");
            echo "<div class='code'>";
            echo "ID | Username | Email | Role | Created<br>";
            echo str_repeat("─", 80) . "<br>";
            foreach ($users as $user) {
                $date = substr($user['created_at'], 0, 10);
                echo $user['id'] . " | " . $user['username'] . " | " . $user['email'] . " | " . $user['role'] . " | " . $date . "<br>";
            }
            echo "</div>";
        } else {
            echo "<div class='result warn'>⚠ No user accounts found</div>";
            echo "<div class='warn'><strong>ACTION REQUIRED:</strong> Click 'Register here' on the login page to create the first admin account</div>";
        }
    } catch (Exception $e) {
        echo "<div class='result fail'>✗ Error checking users: " . $e->getMessage() . "</div>";
    }
} else {
    echo "<div class='result fail'>✗ Cannot check users - database not connected</div>";
}
echo "</div>";

// Check 5: Directory Structure
echo "<div class='section'><h2>5. Directory Permissions</h2>";
$dirs = ['uploads', 'logs', 'uploads/pdfs', 'uploads/signatures', 'uploads/templates'];
foreach ($dirs as $dir) {
    if (is_dir($dir)) {
        if (is_writable($dir)) {
            echo "<div class='result pass'>✓ $dir exists and is writable</div>";
        } else {
            echo "<div class='result warn'>⚠ $dir exists but NOT writable</div>";
        }
    } else {
        echo "<div class='result fail'>✗ $dir does NOT exist</div>";
    }
}
echo "</div>";

// Check 6: Required Classes
echo "<div class='section'><h2>6. PHP Classes</h2>";
$classes = ['Document', 'PDFGenerator', 'EmailHandler', 'Customer', 'Sale', 'ReminderManager'];
foreach ($classes as $class) {
    $file = $class . '.php';
    if (file_exists($file)) {
        echo "<div class='result pass'>✓ $file exists</div>";
    } else {
        echo "<div class='result fail'>✗ $file NOT FOUND</div>";
    }
}
echo "</div>";

// Check 7: Optional Libraries
echo "<div class='section'><h2>7. Optional Libraries (Can be added later)</h2>";
if (file_exists('TCPDF/include/tcpdf.php')) {
    echo "<div class='result pass'>✓ TCPDF installed</div>";
} else {
    echo "<div class='result warn'>⚠ TCPDF not installed (optional - PDF generation can be added later)</div>";
}

if (file_exists('PHPMailer/src/Exception.php')) {
    echo "<div class='result pass'>✓ PHPMailer installed</div>";
} else {
    echo "<div class='result warn'>⚠ PHPMailer not installed (optional - Email reminders can be added later)</div>";
}
echo "</div>";

// Summary
echo "<div class='section' style='background: #d4edda; border-left-color: #28a745;'><h2>✅ Summary</h2>";
echo "<p><strong>Status:</strong> ";

if (!isset($pdo)) {
    echo "❌ CRITICAL - Database not connected. Check config.php credentials.";
} elseif ($count == 0) {
    echo "⚠️ NEEDS ACTION - No user accounts. Click 'Register here' on login page.";
} else {
    echo "✓ READY - System is configured and ready to use.";
}

echo "</p>";
echo "<p><strong>Next Steps:</strong></p>";
echo "<ol>";
if (!isset($pdo)) {
    echo "<li>Verify database credentials in config.php</li>";
    echo "<li>Ensure database server is running</li>";
} elseif ($count == 0) {
    echo "<li>Go to: <code>https://homeofficestyles.com/docusign/login.php</code></li>";
    echo "<li>Click 'Register here'</li>";
    echo "<li>Create admin account (garage name, username, email, password)</li>";
    echo "<li>Click Login and you're ready to go!</li>";
} else {
    echo "<li>Login with your admin account</li>";
    echo "<li>Start creating sales and documents</li>";
}
echo "</ol>";
echo "</div>";

echo "</div></body></html>";
?>
