<?php
require_once 'config/database.php';
require_once 'config/session.php';
require_once 'includes/header.php';

requireLogin();

$pageTitle = 'Customer Management';
$action = $_GET['action'] ?? 'list';
$customerId = $_GET['id'] ?? null;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $pdo = getConnection();
        
        if ($action == 'add' || $action == 'edit') {
            $name = trim($_POST['name']);
            $contactNumber = trim($_POST['contact_number']);
            $email = trim($_POST['email']);
            $address = trim($_POST['address']);
            $gstNumber = trim($_POST['gst_number']);
            
            if (empty($name) || empty($contactNumber)) {
                throw new Exception('Name and Contact Number are required');
            }
            
            if ($action == 'add') {
                $stmt = $pdo->prepare("INSERT INTO customers (name, contact_number, email, address, gst_number) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$name, $contactNumber, $email, $address, $gstNumber]);
                $_SESSION['success_message'] = 'Customer added successfully!';
            } else {
                $stmt = $pdo->prepare("UPDATE customers SET name = ?, contact_number = ?, email = ?, address = ?, gst_number = ? WHERE id = ?");
                $stmt->execute([$name, $contactNumber, $email, $address, $gstNumber, $customerId]);
                $_SESSION['success_message'] = 'Customer updated successfully!';
            }
            
            header('Location: customers.php');
            exit();
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
}

// Handle delete action
if ($action == 'delete' && $customerId) {
    try {
        $pdo = getConnection();
        $stmt = $pdo->prepare("DELETE FROM customers WHERE id = ?");
        $stmt->execute([$customerId]);
        $_SESSION['success_message'] = 'Customer deleted successfully!';
        header('Location: customers.php');
        exit();
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Cannot delete customer. It may be referenced in quotations or invoices.';
    }
}

// Get customer data for editing
$customer = null;
if ($action == 'edit' && $customerId) {
    try {
        $pdo = getConnection();
        $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
        $stmt->execute([$customerId]);
        $customer = $stmt->fetch();
        if (!$customer) {
            $_SESSION['error_message'] = 'Customer not found';
            header('Location: customers.php');
            exit();
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Error loading customer data';
        header('Location: customers.php');
        exit();
    }
}

// Get all customers for listing
$customers = [];
$search = $_GET['search'] ?? '';
try {
    $pdo = getConnection();
    if ($search) {
        $stmt = $pdo->prepare("SELECT * FROM customers WHERE name LIKE ? OR contact_number LIKE ? ORDER BY name");
        $searchTerm = "%$search%";
        $stmt->execute([$searchTerm, $searchTerm]);
    } else {
        $stmt = $pdo->query("SELECT * FROM customers ORDER BY name");
    }
    $customers = $stmt->fetchAll();
} catch (Exception $e) {
    $_SESSION['error_message'] = 'Error loading customers';
}
?>

<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0">
                    <i class="fas fa-users"></i> Customer Management
                </h1>
                <?php if ($action == 'list'): ?>
                    <a href="customers.php?action=add" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add Customer
                    </a>
                <?php else: ?>
                    <a href="customers.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to List
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <?php if ($action == 'list'): ?>
        <!-- Customer List -->
        <div class="row">
            <div class="col-12">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <div class="row align-items-center">
                            <div class="col">
                                <h6 class="m-0 font-weight-bold text-primary">All Customers</h6>
                            </div>
                            <div class="col-auto">
                                <form method="GET" class="d-flex">
                                    <input type="hidden" name="action" value="list">
                                    <input type="text" class="form-control me-2" name="search" 
                                           placeholder="Search customers..." value="<?php echo htmlspecialchars($search); ?>">
                                    <button type="submit" class="btn btn-outline-primary">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if (empty($customers)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                                <p class="text-muted">No customers found.</p>
                                <a href="customers.php?action=add" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Add First Customer
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Name</th>
                                            <th>Contact Number</th>
                                            <th>Email</th>
                                            <th>Address</th>
                                            <th>GST Number</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($customers as $customer): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($customer['name']); ?></td>
                                            <td><?php echo htmlspecialchars($customer['contact_number']); ?></td>
                                            <td><?php echo htmlspecialchars($customer['email']); ?></td>
                                            <td><?php echo htmlspecialchars($customer['address']); ?></td>
                                            <td><?php echo htmlspecialchars($customer['gst_number']); ?></td>
                                            <td>
                                                <a href="customers.php?action=edit&id=<?php echo $customer['id']; ?>" 
                                                   class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="customers.php?action=delete&id=<?php echo $customer['id']; ?>" 
                                                   class="btn btn-sm btn-outline-danger"
                                                   onclick="return confirm('Are you sure you want to delete this customer?')">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
    <?php elseif ($action == 'add' || $action == 'edit'): ?>
        <!-- Add/Edit Customer Form -->
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-<?php echo $action == 'add' ? 'plus' : 'edit'; ?>"></i>
                            <?php echo $action == 'add' ? 'Add New Customer' : 'Edit Customer'; ?>
                        </h6>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="name" class="form-label">Name *</label>
                                    <input type="text" class="form-control" id="name" name="name" 
                                           value="<?php echo htmlspecialchars($customer['name'] ?? ''); ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="contact_number" class="form-label">Contact Number *</label>
                                    <input type="text" class="form-control" id="contact_number" name="contact_number" 
                                           value="<?php echo htmlspecialchars($customer['contact_number'] ?? ''); ?>" required>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="email" class="form-label">Email</label>
                                    <input type="email" class="form-control" id="email" name="email" 
                                           value="<?php echo htmlspecialchars($customer['email'] ?? ''); ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="gst_number" class="form-label">GST Number</label>
                                    <input type="text" class="form-control" id="gst_number" name="gst_number" 
                                           value="<?php echo htmlspecialchars($customer['gst_number'] ?? ''); ?>">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="address" class="form-label">Address</label>
                                <textarea class="form-control" id="address" name="address" rows="3"><?php echo htmlspecialchars($customer['address'] ?? ''); ?></textarea>
                            </div>
                            
                            <div class="d-flex justify-content-end">
                                <a href="customers.php" class="btn btn-secondary me-2">Cancel</a>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> 
                                    <?php echo $action == 'add' ? 'Add Customer' : 'Update Customer'; ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<?php require_once 'includes/footer.php'; ?>
