<?php
session_start();
require_once dirname(__DIR__) . '/includes/functions.php';

billing_require_auth();
$user = billing_current_user();
$organization = billing_current_organization();
if (!$user) {
    billing_redirect('signin.php');
}
if (!$organization || empty($organization['onboarding_completed_at'])) {
    billing_redirect('onboarding.php?step=1');
}

$stats = billing_dashboard_stats((int) $user['id']);
$organizationName = (string) ($organization['organization_name'] ?? 'bala');
$userLabel = (string) ($user['email'] ?? 'billing-user');
$billingTopbarOrganizationName = $organizationName;
$billingTopbarUserLabel = $userLabel;
$editingCustomerId = (int) ($_GET['id'] ?? 0);
$editingCustomer = $editingCustomerId > 0 ? billing_get_customer((int) $user['id'], $editingCustomerId) : null;
if ($editingCustomerId > 0 && !$editingCustomer) {
    billing_flash('success', 'Customer not found.');
    billing_redirect('customers.php');
}
$editingMeta = $editingCustomer ? billing_customer_meta((int) $editingCustomer['id']) : [];
$isEditMode = $editingCustomer !== null;
$salutationOptions = ['Mr.', 'Ms.', 'Mrs.', 'Dr.'];
$countryOptions = ['India'];
$stateOptions = ['Tamil Nadu', 'Kerala', 'Karnataka', 'Maharashtra', 'Delhi', 'West Bengal'];
$errors = [];
$form = [
    'customer_type' => 'Business',
    'salutation' => '',
    'first_name' => '',
    'last_name' => '',
    'company_name' => '',
    'display_name' => '',
    'email' => '',
    'work_phone' => '',
    'mobile' => '',
    'customer_language' => 'English',
    'pan' => '',
    'currency' => 'INR- Indian Rupee',
    'payment_terms' => 'Due on Receipt',
    'enable_portal' => '',
    'website_url' => '',
    'department' => '',
    'designation' => '',
    'x_handle' => '',
    'skype' => '',
    'facebook' => '',
    'billing_attention' => '',
    'billing_country' => '',
    'billing_address_1' => '',
    'billing_address_2' => '',
    'billing_city' => '',
    'billing_state' => '',
    'billing_pin' => '',
    'billing_phone' => '',
    'billing_fax' => '',
    'shipping_attention' => '',
    'shipping_country' => '',
    'shipping_address_1' => '',
    'shipping_address_2' => '',
    'shipping_city' => '',
    'shipping_state' => '',
    'shipping_pin' => '',
    'shipping_phone' => '',
    'shipping_fax' => '',
    'remarks' => '',
    'contact_person_salutation' => '',
    'contact_person_first_name' => '',
    'contact_person_last_name' => '',
    'contact_person_email' => '',
    'contact_person_work_phone' => '',
    'contact_person_mobile' => '',
    'documents' => [],
];

if ($isEditMode) {
    $form = array_merge($form, $editingMeta);
    $form['display_name'] = (string) ($editingCustomer['customer_name'] ?? $form['display_name']);
    $form['email'] = (string) ($editingCustomer['email'] ?? $form['email']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($form as $key => $value) {
        $form[$key] = is_string($_POST[$key] ?? null) ? billing_clean((string) $_POST[$key]) : $value;
    }
    $form['enable_portal'] = !empty($_POST['enable_portal']) ? '1' : '';
    if ($form['display_name'] === '') {
        $errors['display_name'] = 'Enter the Display Name of your customer.';
    }

    if ($errors === []) {
        $form['contact_full_name'] = trim($form['first_name'] . ' ' . $form['last_name']);
        $form['billing_address'] = trim($form['billing_address_1'] . ' ' . $form['billing_address_2'] . ' ' . $form['billing_city']);
        $form['shipping_address'] = trim($form['shipping_address_1'] . ' ' . $form['shipping_address_2'] . ' ' . $form['shipping_city']);
        $form['documents'] = array_values(array_filter(array_merge(
            is_array($form['documents'] ?? null) ? $form['documents'] : [],
            billing_store_uploaded_files('customer_documents', 'customer_docs')
        )));

        if ($isEditMode) {
            $updated = billing_update_customer((int) $editingCustomer['id'], (int) $user['id'], (int) $organization['id'], $form);
            if ($updated) {
                billing_save_customer_meta((int) $editingCustomer['id'], $form);
                billing_flash('success', 'Customer updated successfully.');
                billing_redirect('customers.php?id=' . (int) $editingCustomer['id']);
            }
        } else {
            $customerId = billing_create_customer((int) $user['id'], (int) $organization['id'], $form);
            if ($customerId) {
                billing_save_customer_meta($customerId, $form);
                billing_flash('success', 'Customer created successfully.');
                billing_redirect('customers.php?id=' . $customerId);
            }
        }

        $errors['display_name'] = 'Unable to save the customer right now.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
<title><?php echo $isEditMode ? 'Edit' : 'New Contact'; ?> | Contacts | Zoho Billing</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap">
<link rel="stylesheet" href="Payslip_Project/assets/fontawesome/css/all.min.css">
<link rel="stylesheet" href="assets/billing.css?v=20260507-css-recovery-2">
</head>
<body>
<div class="dashboard-shell customer-shell">
    <?php $billingActiveNav = 'customers'; include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="customer-form-page">
            <form method="post" enctype="multipart/form-data" class="customer-form-card">
                <div class="customer-form-header">
                    <h1><?php echo $isEditMode ? 'Edit Customer' : 'New Customer'; ?></h1>
                </div>
                <?php if (!$isEditMode): ?>
                <div class="customer-prefill-bar"><i class="fa-regular fa-id-card"></i> Prefill Customer details from the GST portal using the Customer's GSTIN. <a href="#">Prefill</a></div>
                <?php endif; ?>
                <?php if (isset($errors['display_name'])): ?>
                    <div class="customer-error-banner"><span><?php echo billing_escape($errors['display_name']); ?></span><i class="fa-solid fa-xmark"></i></div>
                <?php endif; ?>

                <div class="customer-form-grid">
                    <label>Customer Type <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                    <div class="customer-radio-row">
                        <label><input type="radio" name="customer_type" value="Business" <?php echo $form['customer_type'] === 'Business' ? 'checked' : ''; ?>> Business</label>
                        <label><input type="radio" name="customer_type" value="Individual" <?php echo $form['customer_type'] === 'Individual' ? 'checked' : ''; ?>> Individual</label>
                    </div>

                    <label>Primary Contact <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                    <div class="customer-inline-grid customer-inline-grid--three">
                        <select name="salutation">
                            <option value="">Salutation</option>
                            <?php foreach ($salutationOptions as $option): ?>
                                <option value="<?php echo billing_escape($option); ?>" <?php echo $form['salutation'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <input type="text" name="first_name" placeholder="First Name" value="<?php echo billing_escape($form['first_name']); ?>">
                        <input type="text" name="last_name" placeholder="Last Name" value="<?php echo billing_escape($form['last_name']); ?>">
                    </div>

                    <label>Company Name</label>
                    <input type="text" name="company_name" value="<?php echo billing_escape($form['company_name']); ?>">

                    <label class="is-required">Display Name* <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                    <div>
<input type="text" name="display_name" list="customerDisplayNameSuggestions" placeholder="Select or type to add" <?php echo isset($errors['display_name']) ? 'class="is-invalid"' : ''; ?> value="<?php echo billing_escape($form['display_name']); ?>" required>
                        <datalist id="customerDisplayNameSuggestions">
                            <?php if ($form['company_name'] !== ''): ?><option value="<?php echo billing_escape($form['company_name']); ?>"></option><?php endif; ?>
                            <?php if (trim($form['first_name'] . ' ' . $form['last_name']) !== ''): ?><option value="<?php echo billing_escape(trim($form['first_name'] . ' ' . $form['last_name'])); ?>"></option><?php endif; ?>
                        </datalist>
                        <?php if (isset($errors['display_name'])): ?><div class="field-error"><?php echo billing_escape($errors['display_name']); ?></div><?php endif; ?>
                    </div>

                    <label>Email Address <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                    <div class="customer-prefix-field">
                        <span><i class="fa-regular fa-envelope"></i></span>
                        <input type="email" name="email" value="<?php echo billing_escape($form['email']); ?>">
                    </div>

                    <label>Phone <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                    <div class="customer-inline-grid customer-inline-grid--phone">
                        <div class="phone-field"><span>+91</span><input type="text" name="work_phone" placeholder="Work Phone" value="<?php echo billing_escape($form['work_phone']); ?>"></div>
                        <div class="phone-field"><span>+91</span><input type="text" name="mobile" placeholder="Mobile" value="<?php echo billing_escape($form['mobile']); ?>"></div>
                    </div>

                    <label>Customer Language <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                    <select name="customer_language">
                        <option value="English" <?php echo $form['customer_language'] === 'English' ? 'selected' : ''; ?>>English</option>
                    </select>
                </div>

                <div class="customer-tab-bar">
                    <button class="is-active" type="button" data-customer-tab="other">Other Details</button>
                    <button type="button" data-customer-tab="address">Address</button>
                    <button type="button" data-customer-tab="contacts">Contact Persons</button>
                    <button type="button" data-customer-tab="custom">Custom Fields</button>
                    <button type="button" data-customer-tab="reporting">Reporting Tags</button>
                    <button type="button" data-customer-tab="remarks">Remarks</button>
                </div>

                <section class="customer-tab-panel is-active" data-customer-panel="other">
                    <div class="customer-form-grid">
                        <label>PAN <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                        <input type="text" name="pan" value="<?php echo billing_escape($form['pan']); ?>">

                        <label>Currency</label>
                        <select name="currency">
                            <option value="INR- Indian Rupee" <?php echo $form['currency'] === 'INR- Indian Rupee' ? 'selected' : ''; ?>>INR- Indian Rupee</option>
                        </select>

                        <label>Payment Terms</label>
                        <select name="payment_terms">
                            <option value="Due on Receipt" <?php echo $form['payment_terms'] === 'Due on Receipt' ? 'selected' : ''; ?>>Due on Receipt</option>
                        </select>

                        <label>Enable Portal? <i class="fa-solid fa-circle-info customer-label-hint"></i></label>
                        <label class="checkbox-row"><input type="checkbox" name="enable_portal" value="1" <?php echo $form['enable_portal'] === '1' ? 'checked' : ''; ?>> Allow portal access for this customer</label>

                        <label>Documents</label>
                        <div>
                            <input type="file" name="customer_documents[]" id="customerDocuments" accept="image/*,.pdf,.doc,.docx,.xls,.xlsx" multiple hidden>
                            <button class="upload-btn" type="button" data-file-trigger="customerDocuments"><i class="fa-solid fa-arrow-up-from-bracket"></i> Upload File <i class="fa-solid fa-angle-down"></i></button>
                            <div class="helper-text">You can upload a maximum of 10 files, 10MB each</div>
                            <div class="helper-text" id="customerDocumentsList">
                                <?php if (!empty($form['documents']) && is_array($form['documents'])): ?>
                                    <?php echo billing_escape(implode(', ', array_map('basename', $form['documents']))); ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <div class="customer-more-fields" data-customer-extra-fields hidden>
                        <div class="customer-form-grid customer-form-grid--sub">
                            <label>Website URL</label>
                            <div class="customer-prefix-field"><span><i class="fa-solid fa-globe"></i></span><input type="text" name="website_url" placeholder="ex: www.zylker.com" value="<?php echo billing_escape($form['website_url']); ?>"></div>

                            <label>Department</label>
                            <input type="text" name="department" value="<?php echo billing_escape($form['department']); ?>">

                            <label>Designation</label>
                            <input type="text" name="designation" value="<?php echo billing_escape($form['designation']); ?>">

                            <label>X</label>
                            <div>
                                <div class="customer-prefix-field"><span>X</span><input type="text" name="x_handle" value="<?php echo billing_escape($form['x_handle']); ?>"></div>
                                <div class="helper-text">https://x.com/</div>
                            </div>

                            <label>Skype Name/Number</label>
                            <div class="customer-prefix-field"><span><i class="fa-brands fa-skype"></i></span><input type="text" name="skype" value="<?php echo billing_escape($form['skype']); ?>"></div>

                            <label>Facebook</label>
                            <div>
                                <div class="customer-prefix-field"><span><i class="fa-brands fa-facebook-f"></i></span><input type="text" name="facebook" value="<?php echo billing_escape($form['facebook']); ?>"></div>
                                <div class="helper-text">http://www.facebook.com/</div>
                            </div>
                        </div>
                    </div>
                    <a class="customer-add-more" href="#" data-customer-more>Add more details</a>
                </section>

                <section class="customer-tab-panel" data-customer-panel="address">
                    <div class="address-dual-grid">
                        <div>
                            <h3>Billing Address</h3>
                            <div class="customer-form-grid">
                                <label>Attention</label>
                                <input type="text" name="billing_attention" value="<?php echo billing_escape($form['billing_attention']); ?>">

                                <label>Country/Region</label>
                                <select name="billing_country">
                                    <option value="">Select</option>
                                    <?php foreach ($countryOptions as $option): ?>
                                        <option value="<?php echo billing_escape($option); ?>" <?php echo $form['billing_country'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <label>Address</label>
                                <textarea name="billing_address_1" placeholder="Street 1"><?php echo billing_escape($form['billing_address_1']); ?></textarea>

                                <label></label>
                                <textarea name="billing_address_2" placeholder="Street 2"><?php echo billing_escape($form['billing_address_2']); ?></textarea>

                                <label>City</label>
                                <input type="text" name="billing_city" value="<?php echo billing_escape($form['billing_city']); ?>">

                                <label>State</label>
                                <select name="billing_state">
                                    <option value="">Select or type to add</option>
                                    <?php foreach ($stateOptions as $option): ?>
                                        <option value="<?php echo billing_escape($option); ?>" <?php echo $form['billing_state'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <label>Pin Code</label>
                                <input type="text" name="billing_pin" value="<?php echo billing_escape($form['billing_pin']); ?>">

                                <label>Phone</label>
                                <div class="phone-field"><span>+91</span><input type="text" name="billing_phone" value="<?php echo billing_escape($form['billing_phone']); ?>"></div>

                                <label>Fax Number</label>
                                <input type="text" name="billing_fax" value="<?php echo billing_escape($form['billing_fax']); ?>">
                            </div>
                        </div>

                        <div>
                            <h3>Shipping Address <a href="#" data-copy-billing-address><i class="fa-solid fa-arrow-down"></i> Copy billing address</a></h3>
                            <div class="customer-form-grid">
                                <label>Attention</label>
                                <input type="text" name="shipping_attention" value="<?php echo billing_escape($form['shipping_attention']); ?>">

                                <label>Country/Region</label>
                                <select name="shipping_country">
                                    <option value="">Select</option>
                                    <?php foreach ($countryOptions as $option): ?>
                                        <option value="<?php echo billing_escape($option); ?>" <?php echo $form['shipping_country'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <label>Address</label>
                                <textarea name="shipping_address_1" placeholder="Street 1"><?php echo billing_escape($form['shipping_address_1']); ?></textarea>

                                <label></label>
                                <textarea name="shipping_address_2" placeholder="Street 2"><?php echo billing_escape($form['shipping_address_2']); ?></textarea>

                                <label>City</label>
                                <input type="text" name="shipping_city" value="<?php echo billing_escape($form['shipping_city']); ?>">

                                <label>State</label>
                                <select name="shipping_state">
                                    <option value="">Select or type to add</option>
                                    <?php foreach ($stateOptions as $option): ?>
                                        <option value="<?php echo billing_escape($option); ?>" <?php echo $form['shipping_state'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <label>Pin Code</label>
                                <input type="text" name="shipping_pin" value="<?php echo billing_escape($form['shipping_pin']); ?>">

                                <label>Phone</label>
                                <div class="phone-field"><span>+91</span><input type="text" name="shipping_phone" value="<?php echo billing_escape($form['shipping_phone']); ?>"></div>

                                <label>Fax Number</label>
                                <input type="text" name="shipping_fax" value="<?php echo billing_escape($form['shipping_fax']); ?>">
                            </div>
                        </div>
                    </div>
                    <div class="customer-note-box">
                        <strong>Note:</strong>
                        <ul>
                            <li>Add and manage additional addresses from this Customers details section.</li>
                            <li>You can customise how customers' addresses are displayed in transaction PDFs. To do this, go to Settings &gt; Preferences &gt; Customers, and navigate to the Address Format sections.</li>
                        </ul>
                    </div>
                </section>

                <section class="customer-tab-panel" data-customer-panel="contacts">
                    <div class="contact-person-table">
                        <div class="contact-person-head"><span>SALUTATION</span><span>FIRST NAME</span><span>LAST NAME</span><span>EMAIL ADDRESS</span><span>WORK PHONE</span><span>MOBILE</span></div>
                        <div class="contact-person-grid">
                            <div class="contact-person-row">
                                <select name="contact_person_salutation">
                                    <option value=""></option>
                                    <?php foreach ($salutationOptions as $option): ?>
                                        <option value="<?php echo billing_escape($option); ?>" <?php echo $form['contact_person_salutation'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <input type="text" name="contact_person_first_name" value="<?php echo billing_escape($form['contact_person_first_name']); ?>">
                                <input type="text" name="contact_person_last_name" value="<?php echo billing_escape($form['contact_person_last_name']); ?>">
                                <input type="text" name="contact_person_email" value="<?php echo billing_escape($form['contact_person_email']); ?>">
                                <div class="phone-field"><span>+91</span><input type="text" name="contact_person_work_phone" value="<?php echo billing_escape($form['contact_person_work_phone']); ?>"></div>
                                <div class="phone-field"><span>+91</span><input type="text" name="contact_person_mobile" value="<?php echo billing_escape($form['contact_person_mobile']); ?>"></div>
                            </div>
                            <div class="contact-person-actions">
                                <button type="button" aria-label="More options"><i class="fa-solid fa-ellipsis-vertical"></i></button>
                                <button type="button" aria-label="Remove contact person"><i class="fa-regular fa-circle-xmark"></i></button>
                            </div>
                        </div>
                        <button class="contact-add-btn" type="button"><i class="fa-solid fa-circle-plus"></i> Add Contact Person</button>
                    </div>
                </section>

                <section class="customer-tab-panel customer-tab-panel--empty" data-customer-panel="custom">
                    <p>Start adding custom fields for your Customers by going to <em>Settings &rarr; Preferences &rarr; Customers</em>. You can also refine the address format of your Customers from there.</p>
                </section>

                <section class="customer-tab-panel customer-tab-panel--empty" data-customer-panel="reporting">
                    <p>You've not created any Reporting Tags.<br>Start creating reporting tags by going to <em>More Settings &rarr; Reporting Tags</em></p>
                </section>

                <section class="customer-tab-panel" data-customer-panel="remarks">
                    <label class="remarks-label">Remarks <span>(For Internal Use)</span></label>
                    <textarea name="remarks" class="remarks-box"><?php echo billing_escape($form['remarks']); ?></textarea>
                </section>

                <div class="customer-form-footer">
                    <button class="customer-btn customer-btn--green" type="submit">Save</button>
                    <button class="customer-btn" type="submit"><?php echo $isEditMode ? 'Save and Continue' : 'Save and Subscribe'; ?></button>
                    <a class="customer-btn" href="customers.php">Cancel</a>
                </div>
            </form>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>



