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

$company = $conn->query("SELECT * FROM company_master WHERE id = $cid LIMIT 1")->fetch_assoc();

$isAdmin = ($_SESSION['user_role'] ?? '') === 'admin';

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

    $logoPath = $company['logo'] ?? null;
    if (!empty($_FILES['logo']['name'])) {
        $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $fileName = 'company_logo.' . $ext;
        move_uploaded_file($_FILES['logo']['tmp_name'], '../uploads/company/' . $fileName);
        $logoPath = 'uploads/company/' . $fileName;
    }

    $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;
            move_uploaded_file($_FILES['signature']['tmp_name'], '../uploads/company/' . $fileName);
            $signaturePath = 'uploads/company/' . $fileName;
        }
    }

    if ($company) {
        $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=?
            WHERE id=?");
        $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,$company['id']);
    } 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,is_default)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,1)");
        $stmt->bind_param("ssssssssssssss",
            $company_name,$invoice_prefix,$address,$city,$state,$pincode,
            $phone,$email,$gst_no,$pan_no,$logoPath,$bank_name,$account_no,$ifsc);
    }
    $stmt->execute();
    header("Location: company.php?success=1"); exit;
}

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>Company Settings</h2>
</div>

<?php if (isset($_GET['success'])): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i> Company details saved successfully.</div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">

    <!-- Left Column -->
    <div>
        <!-- Identity -->
        <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" value="<?= htmlspecialchars($company['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)</span></label>
                    <?php if (!empty($company['logo'])): ?>
                    <div style="margin-bottom:8px;">
                        <img src="../<?= htmlspecialchars($company['logo']) ?>"
                             style="width:80px;height:80px;object-fit:contain;border:1px solid var(--border);border-radius:8px;padding:4px;">
                    </div>
                    <?php endif; ?>
                    <input type="file" name="logo" accept="image/*" style="padding:6px;">
                </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:8px;">
                        <img src="../<?= htmlspecialchars($company['signature']) ?>"
                             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);display:block;margin-top:4px;">Current signature</span>
                    </div>
                    <?php endif; ?>
                    <input type="file" name="signature" accept="image/*" style="padding:6px;">
                </div>
                <div class="form-group">
                    <label>Address</label>
                    <textarea name="address"><?= htmlspecialchars($company['address'] ?? '') ?></textarea>
                </div>
                <div class="form-row">
                    <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>
        </div>

        <!-- Contact -->
        <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'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" value="<?= htmlspecialchars($company['email'] ?? '') ?>">
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column -->
    <div>
        <!-- Tax -->
        <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" value="<?= htmlspecialchars($company['gst_no'] ?? '') ?>" style="text-transform:uppercase;">
                </div>
                <div class="form-group">
                    <label>PAN Number</label>
                    <input type="text" name="pan_no" value="<?= htmlspecialchars($company['pan_no'] ?? '') ?>" style="text-transform:uppercase;">
                </div>
            </div>
        </div>

        <!-- Bank -->
        <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:var(--info);"></i>Bank Details</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" value="<?= htmlspecialchars($company['ifsc'] ?? '') ?>" style="text-transform:uppercase;">
                </div>
            </div>
        </div>

        <!-- UPI -->
        <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-top:16px;">
    <button type="submit" class="btn btn-primary btn-lg">
        <i class="fas fa-save"></i> Save Company Details
    </button>
</div>
</form>

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