<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';
$username = $_SESSION['username'] ?? 'Guest';

// --- Loyalty settings ---
$loyalty_settings = $conn->query("SELECT * FROM settings WHERE name='loyalty_points_per_MK'")->fetch_assoc();
$points_per_mk = $loyalty_settings['value'] ?? 1; // Default 1 point per MK

// --- Add Customer ---
if (isset($_POST['add_customer'])) {
    $name = $conn->real_escape_string($_POST['name']);
    $phone = $conn->real_escape_string($_POST['phone']);
    $email = $conn->real_escape_string($_POST['email']);
    $address = $conn->real_escape_string($_POST['address']);

    $conn->query("INSERT INTO customers (name, phone, email, address, loyalty_points) 
                  VALUES ('$name', '$phone', '$email', '$address', 0)");

    echo "<script>alert('Customer added successfully');window.location='customers.php';</script>";
    exit;
}

// --- Delete Customer ---
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $conn->query("DELETE FROM customers WHERE id = $id");
    echo "<script>alert('Customer deleted');window.location='customers.php';</script>";
    exit;
}

// --- Search/filter ---
$search = $_GET['search'] ?? '';
$where = '';
if ($search) {
    $s = $conn->real_escape_string($search);
    $where = "WHERE name LIKE '%$s%' OR phone LIKE '%$s%'";
}

// --- Fetch customers ---
$customers = $conn->query("SELECT * FROM customers $where ORDER BY id DESC");

// --- Update loyalty points if sales exist (optional) ---
// This can be triggered in sales_pos.php when completing a sale
?>

<div class="container mt-4">
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>
    <h3 class="text-center">Customer Management & Loyalty</h3>
    <hr>

    <!-- Add Customer Form -->
    <form method="POST" class="row g-3 mb-4">
        <div class="col-md-3"><input type="text" name="name" class="form-control" placeholder="Customer Name" required></div>
        <div class="col-md-3"><input type="text" name="phone" class="form-control" placeholder="Phone"></div>
        <div class="col-md-3"><input type="email" name="email" class="form-control" placeholder="Email"></div>
        <div class="col-md-3"><input type="text" name="address" class="form-control" placeholder="Address"></div>
        <div class="col-md-2 mt-3">
            <button class="btn btn-success w-100" name="add_customer">
                <i class="fa fa-plus"></i> Add Customer
            </button>
        </div>
    </form>

    <!-- Search -->
    <div class="row mb-3">
        <div class="col-md-4">
            <form method="GET">
                <div class="input-group">
                    <input type="text" name="search" class="form-control" placeholder="Search name/phone" value="<?= htmlspecialchars($search) ?>">
                    <button class="btn btn-primary">Search</button>
                </div>
            </form>
        </div>

        <div class="col-md-8 text-end">
            <a href="export_customers.php?type=pdf" class="btn btn-danger btn-sm">Export PDF</a>
            <a href="export_customers.php?type=excel" class="btn btn-success btn-sm">Export Excel</a>
        </div>
    </div>

    <!-- Customer List -->
    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Phone</th>
                <th>Email</th>
                <th>Address</th>
                <th>Loyalty Points</th>
                <th style="width:160px;">Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $i = 1;
            while($row = $customers->fetch_assoc()):
                $points = $row['loyalty_points'] ?? 0;
            ?>
                <tr>
                    <td><?= $i ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= htmlspecialchars($row['phone']) ?></td>
                    <td><?= htmlspecialchars($row['email']) ?></td>
                    <td><?= htmlspecialchars($row['address']) ?></td>
                    <td><?= $points ?></td>
                    <td>
                        <a href="customer_statement.php?id=<?= $row['id'] ?>" class="btn btn-info btn-sm">
                            <i class="fas fa-file-invoice"></i> Statement
                        </a>
                        <a href="edit_customer.php?id=<?= $row['id'] ?>" class="btn btn-primary btn-sm">Edit</a>
                        <a href="customers.php?delete=<?= $row['id'] ?>" onclick="return confirm('Delete this customer?')" class="btn btn-danger btn-sm">Delete</a>
                    </td>
                </tr>
            <?php 
                $i++;
            endwhile; 
            ?>
        </tbody>
    </table>

    <hr>
    <h4>Loyalty Settings</h4>
    <form method="POST" class="row g-3 mb-4">
        <div class="col-md-4">
            <label>Points per MK spent</label>
            <input type="number" name="points_per_mk" value="<?= $points_per_mk ?>" class="form-control" required>
        </div>
        <div class="col-md-2 mt-4">
            <button name="update_loyalty" class="btn btn-success w-100">
                <i class="fa fa-save"></i> Update
            </button>
        </div>
    </form>

<?php
// --- Handle loyalty settings update ---
if(isset($_POST['update_loyalty'])){
    $points_per_mk_new = floatval($_POST['points_per_mk']);
    $exists = $conn->query("SELECT * FROM settings WHERE name='loyalty_points_per_MK'")->num_rows;

    if($exists){
        $conn->query("UPDATE settings SET value='$points_per_mk_new' WHERE name='loyalty_points_per_MK'");
    } else {
        $conn->query("INSERT INTO settings (name, value) VALUES ('loyalty_points_per_MK', '$points_per_mk_new')");
    }

    echo "<script>alert('Loyalty settings updated');window.location='customers.php';</script>";
    exit;
}
?>

</div>
<?php include 'includes/footer.php'; ?>
