<?php
// This script assumes it is included in admin_dashboard.php, 
// so the $conn object (database connection) and $_SESSION data are already available.

// Check if $conn exists (safety check, typically handled by dashboard)
if (!isset($conn)) {
    if (file_exists('config/db_connection.php')) {
        require_once 'config/db_connection.php';
    } else {
        // Fallback or error message if required file is missing
        echo "<div class='message error'>FATAL ERROR: Database connection configuration file not found.</div>";
        exit();
    }
}

$client_message = '';
$user_id = $_SESSION['user_id'] ?? 1; // Default to ID 1 if session ID is missing
$all_clients = [];

// 1. Handle the form submission for creating a new client
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['create_client'])) {
    
    // Sanitize and prepare core client data
    $company_name = $conn->real_escape_string($_POST['company_name']);
    $address = $conn->real_escape_string($_POST['address']);
    $company_email = $conn->real_escape_string($_POST['company_email']);
    $website = $conn->real_escape_string($_POST['website']);
    
    // Sanitize and prepare representative data
    $rep_name = $conn->real_escape_string($_POST['rep_name']);
    $rep_designation = $conn->real_escape_string($_POST['rep_designation']);
    $rep_email = $conn->real_escape_string($_POST['rep_email']);
    
    // --- PHONE NUMBER VALIDATION (FIXED) ---
    $rep_phone_number_raw = trim($_POST['rep_phone_number']);
    $rep_phone_number = $conn->real_escape_string($rep_phone_number_raw);

    // Allows digits, spaces, plus sign (+), and hyphen (-)
    $is_phone_valid = empty($rep_phone_number_raw) || preg_match('/^[0-9\s\+\-]+$/', $rep_phone_number_raw);
    
    // Basic validation
    if (empty($company_name) || empty($rep_name)) {
        $client_message = "<p style='color:red;'>ERROR: Company Name and Representative Name are required fields.</p>";
    } elseif (!$is_phone_valid) {
        $client_message = "<p style='color:red;'>ERROR: Representative Phone Number must contain only numbers, spaces, hyphens, or a '+' sign.</p>";
    } else {
        
        // Prepare the SQL INSERT statement for the clients table
        $sql = "INSERT INTO clients (company_name, address, company_email, website, 
                                     rep_name, rep_designation, rep_email, rep_phone_number) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        
        if ($stmt === false) {
             $client_message = "<p style='color:red;'>Database prepare error: " . $conn->error . "</p>";
        } else {
            // Bind parameters (8 strings: ssssssss)
            $stmt->bind_param("ssssssss", 
                $company_name, $address, $company_email, $website, 
                $rep_name, $rep_designation, $rep_email, $rep_phone_number
            );
        
            if ($stmt->execute()) {
                $client_message = "<p style='color:green;'>Client <b>{$company_name}</b> successfully created and added to the portfolio.</p>";
            } else {
                $client_message = "<p style='color:red;'>Database insert failed: " . $stmt->error . "</p>";
            }
            $stmt->close();
        }
    }
}

// 2. Fetch all clients for display
if (isset($conn)) {
    $sql_clients = "SELECT * FROM clients ORDER BY client_id DESC";
    $result_clients = $conn->query($sql_clients);
    
    if ($result_clients) {
        while ($row = $result_clients->fetch_assoc()) {
            $all_clients[] = $row;
        }
    } else {
        $client_message .= "<p style='color:red;'>ERROR: Could not fetch client list. Ensure the 'clients' table exists.</p>";
    }
}
?>

<style>
    /* Styling specific to this section, reusing form-card from dashboard */
    .section-header {
        margin-bottom: 25px;
        color: #2c3e50;
    }
    .data-container {
        margin-top: 30px;
    }
    .message {
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 4px;
        font-weight: bold;
    }
    .message.success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .message.error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    .form-card input, .form-card select {
        width: 100%;
        box-sizing: border-box;
        padding: 8px;
        border: 1px solid #ccc;
        border-radius: 4px;
    }

    /* Client List Table Styling */
    .client-list-table {
        margin-top: 15px;
        width: 100%;
        border-collapse: collapse;
    }
    .client-list-table th, .client-list-table td {
        padding: 10px;
        border: 1px solid #ecf0f1;
        text-align: left;
    }
    .client-list-table thead th {
        background-color: #7f8c8d;
        color: white;
    }
    .client-list-table tr:nth-child(even) {
        background-color: #f7f7f7;
    }
</style>

<div class="form-card">
    <h2 class="section-header">Client Portfolio Management</h2>
    <h3>1. Create New Client Portfolio Entry</h3>
    <p>Use this form to add a new client and their core portfolio details.</p>
    
    <?php echo $client_message; // Display success or error messages ?>

    <form action="admin_dashboard.php?page=manage_clients" method="post">
        
        <!-- --- Client Details Section --- -->
        <h4>Company Information</h4>
        
        <label for="company_name">Company Name (Required):</label>
        <input type="text" name="company_name" id="company_name" required>
        
        <label for="address">Address:</label>
        <input type="text" name="address" id="address">
        
        <label for="company_email">Company Email:</label>
        <input type="email" name="company_email" id="company_email">
        
        <label for="website">Website:</label>
        <input type="text" name="website" id="website">

        <!-- --- Representative Details Section --- -->
        <h4 style="margin-top: 30px;">Key Representative Information</h4>
        
        <label for="rep_name">Representative's Name (Required):</label>
        <input type="text" name="rep_name" id="rep_name" required>
        
        <label for="rep_designation">Designation:</label>
        <input type="text" name="rep_designation" id="rep_designation">
        
        <label for="rep_email">Representative Email:</label>
        <input type="email" name="rep_email" id="rep_email">
        
        <label for="rep_phone_number">Representative Phone Number (Numbers, +, -, spaces only):</label>
        <!-- HTML5 type="tel" and pattern validation for better user experience -->
        <input type="tel" name="rep_phone_number" id="rep_phone_number" pattern="[0-9\s\+\-]+" title="Phone number must contain only numbers, spaces, hyphens, or a '+' sign.">
        
        <button type="submit" name="create_client">Create Client Portfolio</button>
    </form>
</div>

<!-- -------------------------------------------------------------------- -->
<!-- CLIENT LIST DISPLAY SECTION -->
<!-- -------------------------------------------------------------------- -->

<div class="form-card data-container">
    <h2 class="section-header">All Clients in Portfolio (<?php echo count($all_clients); ?>)</h2>
    
    <?php if (!empty($all_clients)): ?>
        <?php display_client_table($all_clients); ?>
    <?php else: ?>
        <p>No clients have been added to the portfolio yet.</p>
    <?php endif; ?>
</div>

<?php
// Helper function to display the client table
function display_client_table($clients) {
?>
    <table class="client-list-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Company Name</th>
                <th>Representative</th>
                <th>Rep. Contact</th>
                <th>Website</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($clients as $client): ?>
                <tr>
                    <td><?php echo htmlspecialchars($client['client_id']); ?></td>
                    <td>
                        <b><?php echo htmlspecialchars($client['company_name']); ?></b>
                        <br><small><?php echo htmlspecialchars($client['address'] ?? ''); ?></small>
                    </td>
                    <td>
                        <?php echo htmlspecialchars($client['rep_name']); ?>
                        <br><small><?php echo htmlspecialchars($client['rep_designation'] ?? ''); ?></small>
                    </td>
                    <td>
                        <small>Email: <?php echo htmlspecialchars($client['rep_email'] ?? 'N/A'); ?></small>
                        <br><small>Phone: <?php echo htmlspecialchars($client['rep_phone_number'] ?? 'N/A'); ?></small>
                    </td>
                    <td><a href="<?php echo htmlspecialchars($client['website']); ?>" target="_blank"><?php echo htmlspecialchars($client['website']); ?></a></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php
}
?>
