<?php
require_once '../../config/config.php';
require_once '../../config/database.php';

header('Content-Type: application/json');

$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {
    case 'getCustomers':
        getCustomers();
        break;
    case 'addCustomer':
        addCustomer();
        break;
    case 'editCustomer':
        editCustomer();
        break;
    case 'deleteCustomer':
        deleteCustomer();
        break;
    case 'getCustomerDetails':
        getCustomerDetails();
        break;
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}

function getCustomers() {
    global $db;

    $search = isset($_GET['search']) ? $_GET['search'] : '';
    $filter = isset($_GET['filter']) ? $_GET['filter'] : '';

    $query = "SELECT * FROM customers WHERE 1=1";
    if (!empty($search)) {
        $query .= " AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)";
    }
    if (!empty($filter)) {
        $query .= " AND status = ?";
    }

    $stmt = $db->prepare($query);
    $params = [];
    if (!empty($search)) {
        $searchTerm = '%' . $search . '%';
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }
    if (!empty($filter)) {
        $params[] = $filter;
    }

    if ($stmt->execute($params)) {
        $customers = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        echo json_encode(['success' => true, 'data' => $customers]);
    } else {
        error_log("Fetch Customers Error: " . $stmt->error);
        echo json_encode(['success' => false, 'message' => 'Failed to fetch customers: ' . $stmt->error]);
    }
}
function addCustomer() {
    global $db; // Use the $db object from the Database class
    $data = json_decode(file_get_contents("php://input"), true);

    // Debugging: Print the received data
    error_log("Received data: " . print_r($data, true));

    $name = $data['customer_name'];
    $email = $data['email'];
    $phone = $data['phone'];
    $company = $data['company'];
    $address = $data['address'];
    $city = $data['city'];
    $state = $data['state'];
    $zip_code = $data['zip_code'];
    $notes = $data['notes'];

    $query = "INSERT INTO customers (name, email, phone, company, address, city, state, zip_code, notes, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')";

    $stmt = $db->prepare($query);
    if ($stmt->bind_param("sssssssssss", $name, $email, $phone, $company, $address, $city, $state, $zip_code, $notes)) {
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Customer added successfully']);
        } else {
            // Debugging: Print the error message
            error_log($stmt->error);
            echo json_encode(['success' => false, 'message' => 'Failed to add customer']);
        }
    } else {
        // Debugging: Print the error message
        error_log($stmt->error);
        echo json_encode(['success' => false, 'message' => 'Failed to prepare statement']);
    }
}

function editCustomer() {
    global $db;
    $data = json_decode(file_get_contents("php://input"), true);

    $customer_id = $data['customer_id'];
    $name = $data['customer_name'];
    $email = $data['email'];
    $phone = $data['phone'];
    $company = $data['company'];
    $address = $data['address'];
    $city = $data['city'];
    $state = $data['state'];
    $zip_code = $data['zip_code'];
    $notes = $data['notes'];

    $query = "UPDATE customers SET name = ?, email = ?, phone = ?, company = ?, address = ?, city = ?, state = ?, zip_code = ?, notes = ? WHERE id = ?";

    $stmt = $db->prepare($query);
    if ($stmt->execute([$name, $email, $phone, $company, $address, $city, $state, $zip_code, $notes, $customer_id])) {
        echo json_encode(['success' => true, 'message' => 'Customer updated successfully']);
    } else {
        error_log("Update Customer Error: " . $stmt->error);
        echo json_encode(['success' => false, 'message' => 'Failed to update customer']);
    }
}

function deleteCustomer() {
    global $db;
    $data = json_decode(file_get_contents("php://input"), true);

    $customer_id = $data['customer_id'];

    $query = "DELETE FROM customers WHERE id = ?";

    $stmt = $db->prepare($query);
    if ($stmt->execute([$customer_id])) {
        echo json_encode(['success' => true, 'message' => 'Customer deleted successfully']);
    } else {
        error_log("Delete Customer Error: " . $stmt->error);
        echo json_encode(['success' => false, 'message' => 'Failed to delete customer']);
    }
}

function getCustomerDetails() {
    global $db;
    $customer_id = isset($_GET['customer_id']) ? $_GET['customer_id'] : '';

    $query = "SELECT * FROM customers WHERE id = ?";

    $stmt = $db->prepare($query);
    if ($stmt->execute([$customer_id])) {
        $customer = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode(['success' => true, 'data' => $customer]);

    } else {
        error_log("Fetch Customer Details Error: " . $stmt->error);
echo json_encode(['success' => false, 'message' => 'Failed to fetch customer details']);

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

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4>Customer Management</h4>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCustomerModal">
                    <i class="fas fa-plus"></i> Add New Customer
                </button>
            </div>
            <div class="card-body">
                <!-- Search and Filter Section -->
                <div class="row mb-3">
                    <div class="col-md-3">
                        <input type="text" id="customerSearch" class="form-control" placeholder="Search customers...">
                    </div>
                    <div class="col-md-2">
                        <select id="customerFilter" class="form-select">
                            <option value="">All Customers</option>
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>

                <!-- Customers Table -->
                <div class="table-responsive">
                    <table id="customersTable" class="table table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>Total Sales</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Customer Modal -->
<div class="modal fade" id="addCustomerModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Customer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addCustomerForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Customer Name *</label>
                                <input type="text" class="form-control" name="customer_name" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email *</label>
                                <input type="email" class="form-control" name="email" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Phone</label>
                                <input type="tel" class="form-control" name="phone">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Company</label>
                                <input type="text" class="form-control" name="company">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" name="address" rows="2"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">City</label>
                                <input type="text" class="form-control" name="city">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">State</label>
                                <input type="text" class="form-control" name="state">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">ZIP Code</label>
                                <input type="text" class="form-control" name="zip_code">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea class="form-control" name="notes" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Save Customer</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Customer Modal -->
<div class="modal fade" id="editCustomerModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Customer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editCustomerForm">
                <input type="hidden" name="customer_id">
                <div class="modal-body">
                    <!-- Copy the form fields from Add Customer Modal -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Update Customer</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Customer Details Modal -->
<div class="modal fade" id="viewCustomerModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Customer Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Basic Information</h6>
                        <table class="table table-borderless">
                            <tr>
                                <th>Name:</th>
                                <td id="view_customer_name"></td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td id="view_email"></td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td id="view_phone"></td>
                            </tr>
                            <tr>
                                <th>Company:</th>
                                <td id="view_company"></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6>Address Information</h6>
                        <table class="table table-borderless">
                            <tr>
                                <th>Address:</th>
                                <td id="view_address"></td>
                            </tr>
                            <tr>
                                <th>City:</th>
                                <td id="view_city"></td>
                            </tr>
                            <tr>
                                <th>State:</th>
                                <td id="view_state"></td>
                            </tr>
                            <tr>
                                <th>ZIP Code:</th>
                                <td id="view_zip_code"></td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="row mt-4">
                    <div class="col-md-12">
                        <h6>Customer Statistics</h6>
                        <div class="row">
                            <div class="col-md-3">
                                <div class="card bg-primary text-white">
                                    <div class="card-body">
                                        <h6>Total Sales</h6>
                                        <h4 id="view_total_sales">$0.00</h4>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card bg-success text-white">
                                    <div class="card-body">
                                        <h6>Total Invoices</h6>
                                        <h4 id="view_total_invoices">0</h4>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card bg-info text-white">
                                    <div class="card-body">
                                        <h6>Average Invoice</h6>
                                        <h4 id="view_avg_invoice">$0.00</h4>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card bg-warning text-white">
                                    <div class="card-body">
                                        <h6>Outstanding</h6>
                                        <h4 id="view_outstanding">$0.00</h4>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Customer JavaScript -->
<script src="<?php echo SITE_URL; ?>/assets/js/customers.js"></script>

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

$customer_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$customer = getCustomerDetails($customer_id);

if (!$customer) {
    echo "<div class='alert alert-danger'>Customer not found</div>";
    exit;
}
?>

<div class="row">
    <!-- Customer Overview -->
    <div class="col-md-3">
        <div class="card">
            <div class="card-body text-center">
                <div class="customer-avatar mb-3">
                    <img src="<?php echo getCustomerAvatar($customer["email"]); ?>" 
                         class="rounded-circle" style="width: 100px;">
                </div>
                <h4><?php echo htmlspecialchars($customer['customer_name']); ?></h4>
                <p class="text-muted"><?php echo htmlspecialchars($customer['company_name']); ?></p>
                <span class="badge bg-<?php echo $customer['status'] == 'active' ? 'success' : 'danger'; ?>">
                    <?php echo ucfirst($customer['status']); ?>
                </span>
                
                <hr>
                
                <div class="contact-info text-start">
                    <p><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($customer['email']); ?></p>
                    <p><i class="fas fa-phone"></i> <?php echo htmlspecialchars($customer['phone']); ?></p>
                    <p><i class="fas fa-map-marker-alt"></i> <?php echo formatAddress($customer); ?></p>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="card mt-3">
            <div class="card-header">
                <h5>Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <button class="btn btn-primary" onclick="createInvoice(<?php echo $customer_id; ?>)">
                        <i class="fas fa-file-invoice"></i> New Invoice
                    </button>
                    <button class="btn btn-info" onclick="sendEmail(<?php echo $customer_id; ?>)">
                        <i class="fas fa-envelope"></i> Send Email
                    </button>
                    <button class="btn btn-success" onclick="addPayment(<?php echo $customer_id; ?>)">
                        <i class="fas fa-money-bill"></i> Record Payment
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="col-md-9">
        <!-- Statistics Cards -->
        <div class="row">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <h6>Total Sales</h6>
                        <h3><?php echo formatCurrency($customer['total_sales']); ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <h6>Total Invoices</h6>
                        <h3><?php echo $customer['total_invoices']; ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <h6>Average Invoice</h6>
                        <h3><?php echo formatCurrency($customer['avg_invoice_value']); ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <h6>Outstanding</h6>
                        <h3><?php echo formatCurrency($customer['outstanding_amount']); ?></h3>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabs Section -->
        <div class="card mt-3">
            <div class="card-body">
                <ul class="nav nav-tabs" id="customerTabs">
                    <li class="nav-item">
                        <a class="nav-link active" data-bs-toggle="tab" href="#invoices">Invoices</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#transactions">Transactions</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#contacts">Contacts</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#documents">Documents</a>
                    </li>
                </ul>

                <div class="tab-content mt-3">
                    <!-- Invoices Tab -->
                    <div class="tab-pane fade show active" id="invoices">
                        <table class="table table-striped" id="invoicesTable">
                            <thead>
                                <tr>
                                    <th>Invoice #</th>
                                    <th>Date</th>
                                    <th>Due Date</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                        </table>
                    </div>

                    <!-- Transactions Tab -->
                    <div class="tab-pane fade" id="transactions">
                        <table class="table table-striped" id="transactionsTable">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th>Reference</th>
                                    <th>Amount</th>
                                    <th>Balance</th>
                                </tr>
                            </thead>
                        </table>
                    </div>

                    <!-- Contacts Tab -->
                    <div class="tab-pane fade" id="contacts">
                        <button class="btn btn-primary mb-3" onclick="addContact()">
                            <i class="fas fa-plus"></i> Add Contact
                        </button>
                        <div id="contactsList">
                            <!-- Will be populated via AJAX -->
                        </div>
                    </div>

                    <!-- Documents Tab -->
                    <div class="tab-pane fade" id="documents">
                        <form id="uploadDocumentForm" class="mb-3">
                            <div class="row">
                                <div class="col-md-4">
                                    <select class="form-select" name="document_type" required>
                                        <option value="">Select Document Type</option>
                                        <option value="contract">Contract</option>
                                        <option value="id_proof">ID Proof</option>
                                        <option value="tax_document">Tax Document</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <input type="file" class="form-control" name="document" required>
                                </div>
                                <div class="col-md-2">
                                    <button type="submit" class="btn btn-primary w-100">Upload</button>
                                </div>
                            </div>
                        </form>
                        <div id="documentsList">
                            <!-- Will be populated via AJAX -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Contact Modal -->
<div class="modal fade" id="addContactModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Contact</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addContactForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Contact Name</label>
                        <input type="text" class="form-control" name="contact_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Designation</label>
                        <input type="text" class="form-control" name="designation">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Phone</label>
                        <input type="text" class="form-control" name="phone">
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="is_primary" value="1">
                            <label class="form-check-label">Primary Contact</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Save Contact</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
function getCustomerDetails($id) {
    global $db;
    $query = "SELECT * FROM vw_customer_summary WHERE id = " . intval($id);
    $result = $db->query($query);
    return $result->fetch_assoc();
}

function formatAddress($customer) {
    $address = [];
    if ($customer['city']) $address[] = $customer['city'];
    if ($customer['state']) $address[] = $customer['state'];
    if ($customer['country']) $address[] = $customer['country'];
    if ($customer['postal_code']) $address[] = $customer['postal_code'];
    return implode(', ', $address);
}

function getCustomerAvatar($email) {
    $hash = md5(strtolower(trim($email)));
    return "https://www.gravatar.com/avatar/$hash?s=200&d=mp";
}
?>

<script src="<?php echo SITE_URL; ?>/assets/js/customer-profile.js"></script>

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

<div class="row">
    <!-- Report Filters -->
    <div class="col-md-12 mb-4">
        <div class="card">
            <div class="card-header">
                <h4>Customer Analysis</h4>
            </div>
            <div class="card-body">
                <form id="reportFiltersForm">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">Date Range</label>
                                <select class="form-select" name="date_range">
                                    <option value="7">Last 7 Days</option>
                                    <option value="30">Last 30 Days</option>
                                    <option value="90">Last 90 Days</option>
                                    <option value="365">Last Year</option>
                                    <option value="custom">Custom Range</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">Customer Type</label>
                                <select class="form-select" name="customer_type">
                                    <option value="">All Customers</option>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                    <option value="new">New Customers</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">Sort By</label>
                                <select class="form-select" name="sort_by">
                                    <option value="sales">Total Sales</option>
                                    <option value="invoices">Number of Invoices</option>
                                    <option value="average">Average Invoice Value</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-primary d-block w-100">
                                    Generate Report
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="col-md-12 mb-4">
        <div class="row">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <h6>Total Customers</h6>
                        <h3 id="totalCustomers">0</h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <h6>Active Customers</h6>
                        <h3 id="activeCustomers">0</h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <h6>Total Sales</h6>
                        <h3 id="totalSales">$0.00</h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <h6>Average Sale</h6>
                        <h3 id="averageSale">$0.00</h3>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Section -->
    <div class="col-md-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5>Sales Distribution</h5>
            </div>
            <div class="card-body">
                <canvas id="salesDistributionChart"></canvas>
            </div>
        </div>
    </div>

    <div class="col-md-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5>Customer Growth</h5>
            </div>
            <div class="card-body">
                <canvas id="customerGrowthChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Customer Analysis Table -->
    <div class="col-md-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5>Customer Analysis</h5>
                <div class="btn-group">
                    <button class="btn btn-primary" onclick="exportReport('excel')">
                        <i class="fas fa-file-excel"></i> Export Excel
                    </button>
                    <button class="btn btn-danger" onclick="exportReport('pdf')">
                        <i class="fas fa-file-pdf"></i> Export PDF
                    </button>
                </div>
            </div>
            <div class="card-body">
                <table id="customerAnalysisTable" class="table table-striped">
                    <thead>
                        <tr>
                            <th>Customer</th>
                            <th>Total Sales</th>
                            <th>Invoices</th>
                            <th>Average Value</th>
                            <th>Last Purchase</th>
                            <th>Outstanding</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Customer Analysis JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function() {
    // Initialize DataTable
    const analysisTable = $('#customerAnalysisTable').DataTable({
        ajax: {
            url: 'api.php?action=customer_analysis',
            data: function(d) {
                return $.extend({}, d, getReportFilters());
            }
        },
        columns: [
            { 
                data: 'customer_name',
                render: function(data, type, row) {
                    return `<a href="profile.php?id=${row.id}">${data}</a>`;
                }
            },
            { 
                data: 'total_sales',
                render: formatCurrency
            },
            { data: 'invoice_count' },
            { 
                data: 'average_value',
                render: formatCurrency
            },
            { data: 'last_purchase_date' },
            { 
                data: 'outstanding_amount',
                render: formatCurrency
            },
            {
                data: 'status',
                render: function(data) {
                    return `<span class="badge bg-${data === 'active' ? 'success' : 'danger'}">${data}</span>`;
                }
            }
        ],
        order: [[1, 'desc']]
    });

    // Handle Report Filters
    $('#reportFiltersForm').submit(function(e) {
        e.preventDefault();
        updateReport();
    });

    // Initial report load
    updateReport();
});

function updateReport() {
    const filters = getReportFilters();

    // Update summary cards
    $.get('api.php?action=customer_summary', filters, function(response) {
        if(response.success) {
            $('#totalCustomers').text(response.data.total_customers);
            $('#activeCustomers').text(response.data.active_customers);
            $('#totalSales').text(formatCurrency(response.data.total_sales));
            $('#averageSale').text(formatCurrency(response.data.average_sale));
        }
    });

    // Update sales distribution chart
    $.get('api.php?action=sales_distribution', filters, function(response) {
        if(response.success) {
            updateSalesDistributionChart(response.data);
        }
    });

    // Update customer growth chart
    $.get('api.php?action=customer_growth', filters, function(response) {
        if(response.success) {
            updateCustomerGrowthChart(response.data);
        }
    });

    // Refresh analysis table
    $('#customerAnalysisTable').DataTable().ajax.reload();
}

function updateSalesDistributionChart(data) {
    const ctx = document.getElementById('salesDistributionChart').getContext('2d');
    new Chart(ctx, {
        type: 'pie',
        data: {
            labels: data.labels,
            datasets: [{
                data: data.values,
                backgroundColor: [
                    '#4e73df',
                    '#1cc88a',
                    '#36b9cc',
                    '#f6c23e',
                    '#e74a3b'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
}

function updateCustomerGrowthChart(data) {
    const ctx = document.getElementById('customerGrowthChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: data.labels,
            datasets: [{
                label: 'New Customers',
                data: data.values,
                borderColor: '#4e73df',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
}

function getReportFilters() {
    return {
        date_range: $('select[name="date_range"]').val(),
        customer_type: $('select[name="customer_type"]').val(),
        sort_by: $('select[name="sort_by"]').val()
    };
}

function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount);
}

function exportReport(format) {
    const filters = getReportFilters();
    window.location.href = `export_report.php?format=${format}&${$.param(filters)}`;
}
</script>

<?php require_once '../../includes/footer.php'; ?>$(document).ready(function() {

    // Function to fetch customers
    function fetchCustomers(search = '', filter = '') {
        $.ajax({
            url: '<?php echo SITE_URL; ?>/api/api.php?action=getCustomers',
            method: 'GET',
            data: { search: search, filter: filter },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#customersTable').DataTable().clear().rows.add(response.data).draw();
                } else {
                    alert("Error fetching customers: " + response.message);
                }
            },
            error: handleAjaxError
        });
    }

    console.log("DataTables library loaded:", $.fn.DataTable !== undefined);
    
    // Error handling for AJAX requests
    function handleAjaxError(xhr, status, error) {
        console.error("AJAX Error: ", status, error);
        alert("An error occurred while processing your request. Please try again.");
    }

    // Initialize DataTable
    $('#customersTable').DataTable({
        responsive: true,
        columns: [
            { data: 'id' },
            { data: 'name' },
            { data: 'email' },
            { data: 'phone' },
            { data: 'total_sales' },
            { data: 'status' },
            {
                data: null,
                render: function(data) {
                    return `
                        <button class="btn btn-info btn-sm view-customer" data-id="${data.id}"><i class="fas fa-eye"></i></button>
                        <button class="btn btn-warning btn-sm edit-customer" data-id="${data.id}"><i class="fas fa-edit"></i></button>
                        <button class="btn btn-danger btn-sm delete-customer" data-id="${data.id}"><i class="fas fa-trash"></i></button>
                    `;
                }
            }
        ],
        serverSide: false,
        processing: true,
        searching: false,
        ordering: false,
        info: false,
        paging: false
    });

    // Fetch customers on page load
    fetchCustomers();

    // Search and filter functionality
    $('#customerSearch').on('keyup', function() {
        var search = $(this).val();
        var filter = $('#customerFilter').val();
        fetchCustomers(search, filter);
    });

    $('#customerFilter').on('change', function() {
        var search = $('#customerSearch').val();
        var filter = $(this).val();
        fetchCustomers(search, filter);
    });

    // Add Customer Form Submission
    $('#addCustomerForm').on('submit', function(e) {
        e.preventDefault();
        var formData = $(this).serializeJSON();

        $.ajax({
            url: '<?php echo SITE_URL; ?>/api/api.php?action=addCustomer',
            method: 'POST',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#addCustomerModal').modal('hide');
                    fetchCustomers(); // Refresh the customer list
                    alert(response.message);
                } else {
                    alert("Error adding customer: " + response.message);
                }
            },
            error: handleAjaxError
        });
    });

    // Edit Customer Form Submission
    $('#editCustomerForm').on('submit', function(e) {
        e.preventDefault();
        var formData = $(this).serializeJSON();

        $.ajax({
            url: '<?php echo SITE_URL; ?>/api/api.php?action=editCustomer',
            method: 'POST',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#editCustomerModal').modal('hide');
                    fetchCustomers(); // Refresh the customer list
                    alert(response.message);
                } else {
                    alert("Error updating customer: " + response.message);
                }
            },
            error: handleAjaxError
        });
    });

    // Delete Customer
    $(document).on('click', '.delete-customer', function() {
        var customerId = $(this).data('id');
        if (confirm('Are you sure you want to delete this customer?')) {
            $.ajax({
                url: '<?php echo SITE_URL; ?>/api/api.php?action=deleteCustomer',
                method: 'POST',
                data: JSON.stringify({ customer_id: customerId }),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        fetchCustomers(); // Refresh the customer list
                        alert(response.message);
                    } else {
                        alert("Error deleting customer: " + response.message);
                    }
                },
                error: handleAjaxError
            });
        }
    });

    // View Customer Details
    $(document).on('click', '.view-customer', function() {
        var customerId = $(this).data('id');
        $.ajax({
            url: '<?php echo SITE_URL; ?>/api/api.php?action=getCustomerDetails',
            method: 'GET',
            data: { customer_id: customerId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var customer = response.data;
                    $('#view_customer_name').text(customer.name);
                    $('#view_email').text(customer.email);
                    $('#view_phone').text(customer.phone);
                    $('#view_company').text(customer.company);
                    $('#view_address').text(customer.address);
                    $('#view_city').text(customer.city);
                    $('#view_state').text(customer.state);
                    $('#view_zip_code').text(customer.zip_code);
                    $('#view_total_sales').text(formatCurrency(customer.total_sales));
                    $('#view_total_invoices').text(customer.total_invoices);
                    $('#view_avg_invoice').text(formatCurrency(customer.avg_invoice_value));
                    $('#view_outstanding').text(formatCurrency(customer.outstanding_amount));
                    $('#viewCustomerModal').modal('show');
                } else {
                    alert("Error fetching customer details: " + response.message);
                }
            },
            error: handleAjaxError
        });
    });

    // Edit Customer
    $(document).on('click', '.edit-customer', function() {
        var customerId = $(this).data('id');
        $.ajax({
            url: '<?php echo SITE_URL; ?>/api/api.php?action=getCustomerDetails',
            method: 'GET',
            data: { customer_id: customerId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var customer = response.data;
                    $('#editCustomerForm input[name="customer_id"]').val(customer.id);
                    $('#editCustomerForm input[name="customer_name"]').val(customer.name);
                    $('#editCustomerForm input[name="email"]').val(customer.email);
                    $('#editCustomerForm input[name="phone"]').val(customer.phone);
                    $('#editCustomerForm input[name="company"]').val(customer.company);
                    $('#editCustomerForm textarea[name="address"]').val(customer.address);
                    $('#editCustomerForm input[name="city"]').val(customer.city);
                    $('#editCustomerForm input[name="state"]').val(customer.state);
                    $('#editCustomerForm input[name="zip_code"]').val(customer.zip_code);
                    $('#editCustomerForm textarea[name="notes"]').val(customer.notes);
                    $('#editCustomerModal').modal('show');
                } else {
                    alert("Error fetching customer details for editing: " + response.message);
                }
            },
            error: handleAjaxError
        });
    });

    // Format Currency
    function formatCurrency(amount) {
        return '₹' + amount.toFixed(2).replace(/\d(?=(\d{3})+(?!\d))/g, '$&,');
    }
});// assets/js/customer-profile.js
$(document).ready(function() {
    // Initialize DataTables
    const invoicesTable = $('#invoicesTable').DataTable({
        ajax: {
            url: 'api.php',
            data: function(d) {
                d.action = 'get_customer_invoices';
                d.customer_id = getCurrentCustomerId();
            }
        },
        columns: [
            { 
                data: 'invoice_number',
                render: function(data, type, row) {
                    return `<a href="../invoices/view.php?id=${row.id}">${data}</a>`;
                }
            },
            { data: 'invoice_date' },
            { data: 'due_date' },
            { 
                data: 'total_amount',
                render: formatCurrency
            },
            {
                data: 'status',
                render: function(data) {
                    return getStatusBadge(data);
                }
            },
            {
                data: 'id',
                render: function(data, type, row) {
                    return `
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-info" onclick="viewInvoice(${data})">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-primary" onclick="editInvoice(${data})">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-success" onclick="sendInvoice(${data})">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </div>
                    `;
                }
            }
        ],
        order: [[1, 'desc']]
    });

    const transactionsTable = $('#transactionsTable').DataTable({
        ajax: {
            url: 'api.php',
            data: function(d) {
                d.action = 'get_customer_transactions';
                d.customer_id = getCurrentCustomerId();
            }
        },
        columns: [
            { data: 'transaction_date' },
            { 
                data: 'type',
                render: function(data) {
                    const types = {
                        'invoice': 'Invoice',
                        'payment': 'Payment',
                        'credit_note': 'Credit Note'
                    };
                    return types[data] || data;
                }
            },
            { data: 'reference_number' },
            { 
                data: 'amount',
                render: function(data, type, row) {
                    const isPositive = row.type === 'payment';
                    return formatCurrency(data, isPositive);
                }
            },
            { 
                data: 'running_balance',
                render: formatCurrency
            }
        ],
        order: [[0, 'desc']]
    });

    // Load Contacts
    loadContacts();

    // Load Documents
    loadDocuments();

    // Handle Contact Form
    $('#addContactForm').submit(function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'add_contact');
        formData.append('customer_id', getCurrentCustomerId());
        
        $.ajax({
            url: 'api.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if(response.success) {
                    $('#addContactModal').modal('hide');
                    loadContacts();
                    toastr.success('Contact added successfully');
                } else {
                    toastr.error(response.message);
                }
            }
        });
    });

    // Handle Document Upload
    $('#uploadDocumentForm').submit(function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'upload_document');
        formData.append('customer_id', getCurrentCustomerId());
        
        $.ajax({
            url: 'api.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if(response.success) {
                    this.reset();
                    loadDocuments();
                    toastr.success('Document uploaded successfully');
                } else {
                    toastr.error(response.message);
                }
            }
        });
    });
});

function loadContacts() {
    $.get('api.php', {
        action: 'get_contacts',
        customer_id: getCurrentCustomerId()
    }, function(response) {
        if(response.success) {
            let html = '<div class="row">';
            response.data.forEach(contact => {
                html += `
                    <div class="col-md-6 mb-3">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <h5 class="card-title">${contact.contact_name}</h5>
                                    ${contact.is_primary ? '<span class="badge bg-primary">Primary</span>' : ''}
                                </div>
                                <p class="text-muted mb-1">${contact.designation}</p>
                                <p class="mb-1"><i class="fas fa-envelope"></i> ${contact.email}</p>
                                <p class="mb-1"><i class="fas fa-phone"></i> ${contact.phone}</p>
                                <div class="mt-2">
                                    <button class="btn btn-sm btn-primary" onclick="editContact(${contact.id})">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger" onclick="deleteContact(${contact.id})">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            $('#contactsList').html(html);
        }
    });
}

function loadDocuments() {
    $.get('api.php', {
        action: 'get_documents',
        customer_id: getCurrentCustomerId()
    }, function(response) {
        if(response.success) {
            let html = '<div class="table-responsive"><table class="table">';
            html += `
                <thead>
                    <tr>
                        <th>Document Type</th>
                        <th>File Name</th>
                        <th>Uploaded Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
            `;
            response.data.forEach(doc => {
                html += `
                    <tr>
                        <td>${doc.document_type}</td>
                        <td>${doc.file_name}</td>
                        <td>${doc.uploaded_at}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="viewDocument(${doc.id})">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-primary" onclick="downloadDocument(${doc.id})">
                                <i class="fas fa-download"></i>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deleteDocument(${doc.id})">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                `;
            });
            html += '</tbody></table></div>';
            $('#documentsList').html(html);
        }
    });
}

// Helper Functions
function getCurrentCustomerId() {
    return new URLSearchParams(window.location.search).get('id');
}

function formatCurrency(amount, isPositive = true) {
    const value = Math.abs(parseFloat(amount));
    const formatted = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(value);
    
    return isPositive ? formatted : `(${formatted})`;
}

function getStatusBadge(status) {
    const colors = {
        'paid': 'success',
        'unpaid': 'danger',
        'partial': 'warning',
        'cancelled': 'secondary'
    };
    return `<span class="badge bg-${colors[status] || 'primary'}">${status}</span>`;
}

// Action Functions
function createInvoice(customerId) {
    window.location.href = `../invoices/create.php?customer_id=${customerId}`;
}

function sendEmail(customerId) {
    // Implement email sending functionality
}

function addPayment(customerId) {
    // Implement payment recording functionality
}

function editContact(contactId) {
    // Implement contact editing functionality
}

function deleteContact(contactId) {
    if(confirm('Are you sure you want to delete this contact?')) {
        $.post('api.php', {
            action: 'delete_contact',
            contact_id: contactId
        }, function(response) {
            if(response.success) {
                loadContacts();
                toastr.success('Contact deleted successfully');
            } else {
                toastr.error(response.message);
            }
        });
    }
}

function viewDocument(docId) {
    window.open(`view_document.php?id=${docId}`, '_blank');
}

function downloadDocument(docId) {
    window.location.href = `download_document.php?id=${docId}`;
}

function deleteDocument(docId) {
    if(confirm('Are you sure you want to delete this document?')) {
        $.post('api.php', {
            action: 'delete_document',
            document_id: docId
        }, function(response) {
            if(response.success) {
                loadDocuments();
                toastr.success('Document deleted successfully');
            } else {
                toastr.error(response.message);
            }
        });
    }
}
    I need a Proper Database tables command views and procedures