<?php
require_once '../../includes/auth.php';
require_once '../../db.php';
require_once '../../includes/config.php';

$editId  = (int)($_GET['id'] ?? 0);
$isEdit  = $editId > 0;
$company = null;

if ($isEdit) {
    $company = $conn->query("SELECT * FROM company_master WHERE id = $editId LIMIT 1")->fetch_assoc();
    if (!$company) {
        header("Location: index.php?error=" . urlencode("Company not found."));
        exit;
    }
}

// Ensure uploads directory exists
$uploadDir = __DIR__ . '/../../uploads/company/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $company_name = trim($_POST['company_name'] ?? '');
    $address      = trim($_POST['address']      ?? '');
    $city         = trim($_POST['city']         ?? '');
    $state        = trim($_POST['state']        ?? '');
    $pincode      = trim($_POST['pincode']      ?? '');
    $phone        = trim($_POST['phone']        ?? '');
    $email        = trim($_POST['email']        ?? '');
    $gst_no       = strtoupper(trim($_POST['gst_no']  ?? ''));
    $pan_no       = strtoupper(trim($_POST['pan_no']  ?? ''));
    $bank_name    = trim($_POST['bank_name']    ?? '');
    $account_no   = trim($_POST['account_no']   ?? '');
    $ifsc         = strtoupper(trim($_POST['ifsc'] ?? ''));
    $upi_id       = trim($_POST['upi_id']       ?? '');
    $upi_name     = trim($_POST['upi_name']     ?? '');
    $invoice_prefix = strtoupper(trim($_POST['invoice_prefix'] ?? ''));
    $is_default     = isset($_POST['is_default']) ? 1 : 0;

    if (empty($company_name)) {
        $formError = "Company name is required.";
    } else {
        // Handle logo upload
        $logoPath = $company['logo'] ?? null;
        if (!empty($_FILES['logo']['name']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $ext      = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            $allowed  = ['jpg','jpeg','png','gif','webp','svg'];
            if (in_array($ext, $allowed)) {
                $safeName = preg_replace('/[^a-z0-9_-]/i', '_', $company_name);
                $fileName = $safeName . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $uploadDir . $fileName)) {
                    $logoPath = 'uploads/company/' . $fileName;
                }
            }
        }

        // Handle signature upload
        $signaturePath = $company['signature'] ?? null;
        if (!empty($_FILES['signature']['name']) && $_FILES['signature']['error'] === UPLOAD_ERR_OK) {
            $ext     = strtolower(pathinfo($_FILES['signature']['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg','jpeg','png','gif','webp','svg'];
            if (in_array($ext, $allowed)) {
                $safeName = preg_replace('/[^a-z0-9_-]/i', '_', $company_name);
                $fileName = $safeName . '_sign_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['signature']['tmp_name'], $uploadDir . $fileName)) {
                    $signaturePath = 'uploads/company/' . $fileName;
                }
            }
        }

        // If is_default selected, unset other defaults first
        if ($is_default) {
            $conn->query("UPDATE company_master SET is_default = 0");
        }

        if ($isEdit) {
            $stmt = $conn->prepare("
                UPDATE company_master SET
                    company_name=?, invoice_prefix=?, address=?, city=?, state=?, pincode=?,
                    phone=?, email=?, gst_no=?, pan_no=?, logo=?,
                    bank_name=?, account_no=?, ifsc=?, upi_id=?, upi_name=?,
                    signature=?, is_default=?
                WHERE id=?
            ");
            $stmt->bind_param(
                "sssssssssssssssssii",
                $company_name, $invoice_prefix, $address, $city, $state, $pincode,
                $phone, $email, $gst_no, $pan_no, $logoPath,
                $bank_name, $account_no, $ifsc, $upi_id, $upi_name,
                $signaturePath, $is_default, $editId
            );
        } else {
            $stmt = $conn->prepare("
                INSERT INTO company_master
                    (company_name, invoice_prefix, address, city, state, pincode, phone, email,
                     gst_no, pan_no, logo, bank_name, account_no, ifsc,
                     upi_id, upi_name, signature, is_default)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ");
            $stmt->bind_param(
                "sssssssssssssssssi",
                $company_name, $invoice_prefix, $address, $city, $state, $pincode,
                $phone, $email, $gst_no, $pan_no, $logoPath,
                $bank_name, $account_no, $ifsc, $upi_id, $upi_name,
                $signaturePath, $is_default
            );
        }
        $stmt->execute();
        header("Location: index.php?success=1");
        exit;
    }
}

// Bank accounts for this company (if editing)
$bankAccounts = [];
if ($isEdit) {
    $ba = $conn->query("SELECT * FROM company_bank_accounts WHERE company_id = $editId ORDER BY is_primary DESC, sort_order ASC, id ASC");
    if ($ba) { $bankAccounts = $ba->fetch_all(MYSQLI_ASSOC); }
}

require_once '../../includes/header.php';
require_once '../../includes/sidebar.php';
?>

<div class="page-header">
    <h2>
        <i class="fas fa-building" style="color:var(--primary);margin-right:8px;"></i>
        <?= $isEdit ? 'Edit Company' : 'Add Company' ?>
    </h2>
    <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back to Companies</a>
</div>

<?php if (!empty($formError)): ?>
<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($formError) ?></div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data">

<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px;">

    <!-- Left Column -->
    <div>
        <!-- Identity Panel -->
        <div class="panel" style="margin-bottom:16px;">
            <div class="panel-header">
                <span class="panel-title"><i class="fas fa-id-card" style="margin-right:7px;color:var(--primary);"></i>Company Identity</span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label>Company Name <span style="color:var(--danger)">*</span></label>
                    <input type="text" name="company_name" required
                           value="<?= htmlspecialchars($company['company_name'] ?? '') ?>"
                           placeholder="Enter company name">
                </div>
                <div class="form-group" style="max-width:180px;">
                    <label>Invoice Prefix <span style="color:var(--text-muted);font-weight:400;text-transform:none;font-size:11px;">(auto-derived if blank)</span></label>
                    <input type="text" name="invoice_prefix" maxlength="5" style="text-transform:uppercase;"
                           value="<?= htmlspecialchars($company['invoice_prefix'] ?? '') ?>"
                           placeholder="e.g. MSH">
                </div>
                <div class="form-group">
                    <label>Logo <span style="color:var(--text-muted);font-weight:400;text-transform:none;">(square image recommended)</span></label>
                    <?php if (!empty($company['logo'])): ?>
                    <div style="margin-bottom:10px;display:flex;align-items:center;gap:12px;">
                        <img src="../../<?= htmlspecialchars($company['logo']) ?>"
                             id="logoPreview"
                             style="width:72px;height:72px;object-fit:contain;border:1px solid var(--border);border-radius:8px;padding:4px;background:#f8fafc;">
                        <span style="font-size:12px;color:var(--text-muted);">Current logo</span>
                    </div>
                    <?php else: ?>
                    <div style="margin-bottom:10px;">
                        <img id="logoPreview" src="" alt=""
                             style="display:none;width:72px;height:72px;object-fit:contain;border:1px solid var(--border);border-radius:8px;padding:4px;background:#f8fafc;">
                    </div>
                    <?php endif; ?>
                    <input type="file" name="logo" accept="image/*" style="padding:6px;"
                           onchange="previewLogo(this)">
                </div>
                <div class="form-group">
                    <label>Authorised Signatory Signature <span style="color:var(--text-muted);font-weight:400;text-transform:none;">(transparent PNG recommended)</span></label>
                    <?php if (!empty($company['signature'])): ?>
                    <div style="margin-bottom:10px;display:flex;align-items:center;gap:12px;">
                        <img src="../../<?= htmlspecialchars($company['signature']) ?>"
                             id="signPreview"
                             style="height:50px;max-width:180px;object-fit:contain;border:1px solid var(--border);border-radius:6px;padding:4px;background:#f8fafc;">
                        <span style="font-size:12px;color:var(--text-muted);">Current signature</span>
                    </div>
                    <?php else: ?>
                    <div style="margin-bottom:10px;">
                        <img id="signPreview" src="" alt=""
                             style="display:none;height:50px;max-width:180px;object-fit:contain;border:1px solid var(--border);border-radius:6px;padding:4px;background:#f8fafc;">
                    </div>
                    <?php endif; ?>
                    <input type="file" name="signature" accept="image/*" style="padding:6px;"
                           onchange="previewSign(this)">
                </div>
                <div class="form-group">
                    <label>Address</label>
                    <textarea name="address" rows="3" placeholder="Street address"><?= htmlspecialchars($company['address'] ?? '') ?></textarea>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                    <div class="form-group">
                        <label>City</label>
                        <input type="text" name="city" value="<?= htmlspecialchars($company['city'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>State</label>
                        <input type="text" name="state" value="<?= htmlspecialchars($company['state'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-group" style="max-width:160px;">
                    <label>Pincode</label>
                    <input type="text" name="pincode" value="<?= htmlspecialchars($company['pincode'] ?? '') ?>">
                </div>
                <div class="form-group" style="margin-top:4px;">
                    <label style="display:flex;align-items:center;gap:8px;font-weight:500;text-transform:none;letter-spacing:0;cursor:pointer;">
                        <input type="checkbox" name="is_default" <?= !empty($company['is_default']) ? 'checked' : '' ?>>
                        Set as Default Company
                    </label>
                    <p style="font-size:11px;color:var(--text-muted);margin-top:4px;">The default company is used for new sessions when no active company is set.</p>
                </div>
            </div>
        </div>

        <!-- Contact Panel -->
        <div class="panel">
            <div class="panel-header">
                <span class="panel-title"><i class="fas fa-phone" style="margin-right:7px;color:var(--success);"></i>Contact</span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label>Phone</label>
                    <input type="text" name="phone" value="<?= htmlspecialchars($company['phone'] ?? '') ?>" placeholder="+91 98765 43210">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" value="<?= htmlspecialchars($company['email'] ?? '') ?>" placeholder="company@example.com">
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column -->
    <div>
        <!-- Tax Panel -->
        <div class="panel" style="margin-bottom:16px;">
            <div class="panel-header">
                <span class="panel-title"><i class="fas fa-percent" style="margin-right:7px;color:var(--warning);"></i>Tax Details</span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label>GST Number</label>
                    <input type="text" name="gst_no" style="text-transform:uppercase;"
                           value="<?= htmlspecialchars($company['gst_no'] ?? '') ?>"
                           placeholder="22AAAAA0000A1Z5" maxlength="15">
                </div>
                <div class="form-group">
                    <label>PAN Number</label>
                    <input type="text" name="pan_no" style="text-transform:uppercase;"
                           value="<?= htmlspecialchars($company['pan_no'] ?? '') ?>"
                           placeholder="AAAAA0000A" maxlength="10">
                </div>
            </div>
        </div>

        <!-- Bank Panel (legacy single account) -->
        <div class="panel" style="margin-bottom:16px;">
            <div class="panel-header">
                <span class="panel-title"><i class="fas fa-university" style="margin-right:7px;color:#0284c7;"></i>Default Bank Details <span style="font-weight:400;font-size:11px;color:var(--text-muted);">(legacy fallback)</span></span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label>Bank Name</label>
                    <input type="text" name="bank_name" value="<?= htmlspecialchars($company['bank_name'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Account Number</label>
                    <input type="text" name="account_no" value="<?= htmlspecialchars($company['account_no'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>IFSC Code</label>
                    <input type="text" name="ifsc" style="text-transform:uppercase;"
                           value="<?= htmlspecialchars($company['ifsc'] ?? '') ?>">
                </div>
            </div>
        </div>

        <!-- UPI Panel -->
        <div class="panel">
            <div class="panel-header">
                <span class="panel-title"><i class="fas fa-qrcode" style="margin-right:7px;color:#7c3aed;"></i>UPI Payment</span>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label>UPI ID</label>
                    <input type="text" name="upi_id"
                           value="<?= htmlspecialchars($company['upi_id'] ?? '') ?>"
                           placeholder="example@upi">
                </div>
                <div class="form-group">
                    <label>UPI Display Name</label>
                    <input type="text" name="upi_name"
                           value="<?= htmlspecialchars($company['upi_name'] ?? '') ?>">
                </div>
            </div>
        </div>
    </div>
</div>

<div style="margin-bottom:24px;display:flex;gap:10px;">
    <button type="submit" class="btn btn-primary">
        <i class="fas fa-save"></i> <?= $isEdit ? 'Update Company' : 'Save Company' ?>
    </button>
    <a href="index.php" class="btn btn-secondary">Cancel</a>
</div>

</form>

<?php if ($isEdit): ?>
<!-- Bank Accounts Section -->
<div class="panel" style="margin-bottom:24px;">
    <div class="panel-header" style="display:flex;align-items:center;justify-content:space-between;">
        <span class="panel-title"><i class="fas fa-university" style="margin-right:7px;color:var(--primary);"></i>Bank Accounts</span>
        <a href="../bank_accounts.php?company_id=<?= $editId ?>&action=add"
           class="btn btn-sm btn-primary"><i class="fas fa-plus"></i> Add Bank Account</a>
    </div>
    <?php if (empty($bankAccounts)): ?>
    <div style="padding:24px;text-align:center;color:var(--text-muted);">
        <i class="fas fa-university" style="font-size:28px;opacity:0.3;margin-bottom:8px;display:block;"></i>
        No bank accounts yet. <a href="../bank_accounts.php?company_id=<?= $editId ?>&action=add">Add one</a>.
    </div>
    <?php else: ?>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Bank</th>
                    <th>Account No</th>
                    <th>IFSC</th>
                    <th>Type</th>
                    <th>UPI ID</th>
                    <th style="text-align:center;">Primary</th>
                    <th style="text-align:center;">On Invoice</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($bankAccounts as $b): ?>
            <tr>
                <td>
                    <strong><?= htmlspecialchars($b['bank_name']) ?></strong>
                    <?php if ($b['account_holder']): ?><br><small><?= htmlspecialchars($b['account_holder']) ?></small><?php endif; ?>
                </td>
                <td><?= htmlspecialchars($b['account_no']) ?></td>
                <td><?= htmlspecialchars($b['ifsc']) ?></td>
                <td><?= htmlspecialchars($b['account_type']) ?></td>
                <td><?= htmlspecialchars($b['upi_id'] ?? '') ?></td>
                <td style="text-align:center;"><?= $b['is_primary'] ? '<span class="badge badge-success">Yes</span>' : '—' ?></td>
                <td style="text-align:center;"><?= $b['display_on_invoice'] ? '<span class="badge badge-success">Yes</span>' : '<span class="badge badge-gray">No</span>' ?></td>
                <td>
                    <div class="action-links" style="justify-content:center;">
                        <a href="../bank_accounts.php?company_id=<?= $editId ?>&action=edit&id=<?= $b['id'] ?>"
                           class="action-btn edit" title="Edit"><i class="fas fa-edit"></i></a>
                        <a href="../bank_accounts.php?company_id=<?= $editId ?>&action=delete&id=<?= $b['id'] ?>"
                           class="action-btn delete" title="Delete"
                           onclick="return confirm('Delete this bank account?')"><i class="fas fa-trash-alt"></i></a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<script>
function previewLogo(input) {
    var preview = document.getElementById('logoPreview');
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}
function previewSign(input) {
    var preview = document.getElementById('signPreview');
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}
</script>

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