<?php
// Start session early for role-based debug output
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Top-level error handler for fatal errors
set_exception_handler(function($e) {
    echo '<div style="background:#fff3cd;color:#856404;padding:20px;margin:20px;border:2px solid #ffeeba;font-size:1.2em;">';
    echo '<strong>Fatal Error:</strong> ' . htmlspecialchars($e->getMessage());
    echo '<br><strong>File:</strong> ' . $e->getFile() . ' (Line ' . $e->getLine() . ')';
    echo '</div>';
    exit;
});

date_default_timezone_set('Asia/Colombo');
include '../config.php';

// Add customer_phone column to sales table if it doesn't exist

// Only add customer_phone column if it does not exist
$check_column = $conn->query("SHOW COLUMNS FROM sales LIKE 'customer_phone'");
if ($check_column && $check_column->num_rows == 0) {
    $conn->query("ALTER TABLE sales ADD COLUMN customer_phone VARCHAR(20) DEFAULT NULL");
}

// Auto-sync phone numbers from sales that don't have customer records (with error handling)
try {
    $sync_query = "
        INSERT IGNORE INTO customers (name, phone, created_at) 
        SELECT DISTINCT 
            CONCAT('Customer ', s.customer_phone) as name,
            s.customer_phone as phone,
            NOW() as created_at
        FROM sales s 
        WHERE s.customer_phone IS NOT NULL 
        AND s.customer_phone != '' 
        AND s.customer_phone NOT IN (SELECT phone FROM customers WHERE phone IS NOT NULL)
    ";
    $conn->query($sync_query);
} catch (Exception $e) {
    // If sync fails, continue without error to prevent page crash
    error_log("Customer sync error: " . $e->getMessage());
}

// Handle add/edit customer
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $address = $_POST['address'];
    
    if ($id) {
        // Update existing customer
        $stmt = $conn->prepare('UPDATE customers SET name = ?, phone = ?, email = ?, address = ? WHERE id = ?');
        $stmt->bind_param('ssssi', $name, $phone, $email, $address, $id);
    } else {
        // Check if phone already exists
        if (!empty($phone)) {
            $check_stmt = $conn->prepare('SELECT id FROM customers WHERE phone = ?');
            $check_stmt->bind_param('s', $phone);
            $check_stmt->execute();
            $existing = $check_stmt->get_result()->fetch_assoc();
            $check_stmt->close();
            
            if ($existing) {
                $error = 'A customer with this phone number already exists!';
            } else {
                // Auto-generate name if not provided
                $auto_name = 'Customer ' . substr($phone, -4);
                $stmt = $conn->prepare('INSERT INTO customers (name, phone) VALUES (?, ?)');
                $stmt->bind_param('ss', $auto_name, $phone);
            }
        }
    }
    
    if (isset($stmt) && $stmt->execute()) {
        $message = $id ? 'Customer updated successfully!' : 'Customer added successfully!';
    } elseif (!isset($error)) {
        $error = 'Error: ' . ($stmt->error ?? 'Unknown error');
    }
    if (isset($stmt)) $stmt->close();
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $conn->prepare('DELETE FROM customers WHERE id = ?');
    $stmt->bind_param('i', $id);
    if ($stmt->execute()) {
        $message = 'Customer deleted successfully!';
    } else {
        $error = 'Error deleting customer!';
    }
    $stmt->close();
}

// Get customer for editing
$edit_customer = null;
if (isset($_GET['edit'])) {
    $id = $_GET['edit'];
    $stmt = $conn->prepare('SELECT * FROM customers WHERE id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $edit_customer = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

// Fetch all customers (including auto-synced ones) with error handling
try {
    $result = $conn->query('
        SELECT c.*, 
               COUNT(s.id) as total_purchases, 
               COALESCE(SUM(s.total_amount), 0) as total_spent,
               MAX(s.sale_date) as last_purchase,
               CASE WHEN c.name LIKE "Customer %" THEN 1 ELSE 0 END as is_auto_synced
        FROM customers c 
        LEFT JOIN sales s ON c.phone = s.customer_phone
        GROUP BY c.id 
        ORDER BY is_auto_synced ASC, c.name
    ');
} catch (Exception $e) {
    // Fallback to simple query if complex one fails
    $result = $conn->query('SELECT *, 0 as total_purchases, 0 as total_spent, NULL as last_purchase, 0 as is_auto_synced FROM customers ORDER BY name');
}

// Auto-sync: Find sales with phone numbers but no customer_id and try to link/create customers
try {
    // Check if customer_phone column exists
    $column_check = $conn->query("SHOW COLUMNS FROM sales LIKE 'customer_phone'");
    if ($column_check && $column_check->num_rows > 0) {
        // Get sales with phone numbers but no customer_id
        $unlinked_sales = $conn->query("
            SELECT DISTINCT customer_phone 
            FROM sales 
            WHERE customer_phone IS NOT NULL 
            AND customer_phone != '' 
            AND customer_id IS NULL
        ");
        
        if ($unlinked_sales && $unlinked_sales->num_rows > 0) {
            while ($sale = $unlinked_sales->fetch_assoc()) {
                $phone = $sale['customer_phone'];
                
                // Check if customer with this phone already exists
                $check_customer = $conn->prepare("SELECT id FROM customers WHERE phone = ?");
                $check_customer->bind_param("s", $phone);
                $check_customer->execute();
                $existing = $check_customer->get_result();
                
                if ($existing->num_rows == 0) {
                    // Create new customer
                    $auto_name = "Customer " . substr($phone, -4);
                    $insert_customer = $conn->prepare("INSERT INTO customers (name, phone, created_at) VALUES (?, ?, NOW())");
                    $insert_customer->bind_param("ss", $auto_name, $phone);
                    $insert_customer->execute();
                    $customer_id = $conn->insert_id;
                    $insert_customer->close();
                } else {
                    $customer_id = $existing->fetch_assoc()['id'];
                }
                $check_customer->close();
                
                // Link all sales with this phone to the customer
                $update_sales = $conn->prepare("UPDATE sales SET customer_id = ? WHERE customer_phone = ? AND customer_id IS NULL");
                $update_sales->bind_param("is", $customer_id, $phone);
                $update_sales->execute();
                $update_sales->close();
            }
            $unlinked_sales->close();
        }
    }
    $column_check->close();
} catch (Exception $e) {
    // Log error to file and set user-friendly error message
    file_put_contents(__DIR__ . '/auto_sync_error.log', date('Y-m-d H:i:s') . ' - ' . $e->getMessage() . "\n", FILE_APPEND);
    $error = 'A system error occurred during customer auto-sync. Please contact support.';
    // Show detailed error for admins/managers
    if (isset($_SESSION['role']) && ($_SESSION['role'] === 'admin' || $_SESSION['role'] === 'manager')) {
        $error .= '<br><strong>Debug:</strong> ' . htmlspecialchars($e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Customers - Dilrukshi Tex</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">
    <style>
        body { background: #f8f9fa; }
        .container { margin-top: 40px; }
        .table th, .table td { vertical-align: middle; }
        .customer-avatar { width: 40px; height: 40px; border-radius: 50%; background: #007bff; color: white; display: flex; align-items: center; justify-content: center; font-weight: bold; }
    </style>
</head>
<body>
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="fw-bold"><i class="fas fa-users"></i> Customers</h1>
            <div>
                <a href="../pos/" class="btn btn-success me-2"><i class="fas fa-cash-register"></i> POS</a>
                <a href="../" class="btn btn-secondary"><i class="fas fa-home"></i> Dashboard</a>
            </div>
        </div>
        
        <?php if (isset($message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?= $error ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- Auto-Sync Status -->
        <div class="row mb-4">
            <div class="col-md-12">
                <div class="alert alert-info">
                    <i class="fas fa-sync-alt"></i> <strong>Auto-Sync:</strong> Phone numbers from POS sales are automatically added to the customer database. 
                    Auto-synced customers are marked with <span class="badge bg-warning">AUTO</span> and can be updated with full details.
                </div>
            </div>
        </div>
        
        <div class="card mb-4">
            <div class="card-header bg-info text-white">
                <i class="fas fa-user-plus"></i> <?= $edit_customer ? 'Edit Customer' : 'Add New Customer' ?>
            </div>
            <div class="card-body">
                <form method="post" class="row g-3">
                    <?php if ($edit_customer): ?>
                    <input type="hidden" name="id" value="<?= $edit_customer['id'] ?>">
                    <?php endif; ?>
                    <div class="col-md-4">
                        <label class="form-label">Mobile Number</label>
                        <input type="tel" name="phone" class="form-control" value="<?= $edit_customer['phone'] ?? '' ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-info w-100">
                            <i class="fas fa-save"></i> <?= $edit_customer ? 'Update' : 'Add' ?>
                        </button>
                    </div>
                    <div class="col-12">
                        <a href="?" class="btn btn-secondary">Cancel Edit</a>
                    </div>
                </form>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <span><i class="fas fa-address-book"></i> Customer Database</span>
                <small>Total: <?= $result->num_rows ?> customers</small>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped table-hover mb-0">
                        <thead class="table-dark">
                            <tr>
                                <th>Customer</th>
                            <th>Mobile Number</th>
                            <th>Purchases</th>
                            <th>Total Spent</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($row['phone']) ?></td>
                                <td><?= $row['total_purchases'] ?></td>
                                <td>Rs <?= number_format($row['total_spent'], 2) ?></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
