<?php
file_put_contents("debug.txt", print_r($_SERVER, true) . "\n\n" . print_r($_POST, true) . "\n\n" . print_r($_FILES, true));

require_once __DIR__ . '/../src/db.php';
date_default_timezone_set('Asia/Kolkata'); 
require_once __DIR__ . '/../src/session.php';

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $business_name = trim($_POST['business_name']);
    $phone         = trim($_POST['phone']);
    $address       = trim($_POST['address']);
    $password_hash = password_hash($_POST['password'], PASSWORD_BCRYPT);

    // -----------------------------
    // File Upload Handling
    // -----------------------------
    $logo_name = null;

    if (!empty($_FILES['logo']['name'])) {
        $upload_dir = dirname(__DIR__) . "/src/api/uploads/";

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        chmod($upload_dir, 0777);

        $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $logo_name = "logo_" . time() . "." . $ext;

        move_uploaded_file($_FILES['logo']['tmp_name'], $upload_dir . $logo_name);
    }

    // -----------------------------
    // Check if business already exists
    // -----------------------------
    $exists = one("SELECT * FROM settings WHERE phone = ?", [$phone]);

    if ($exists) {
        $error = "⚠️ Phone number already exists!";
    } else {
        // Insert new business including logo
        $insert = query(
            "INSERT INTO settings (business_name, address, phone, password, gstin, gst_rate, gst_applicable, logo)
             VALUES (?, ?, ?, ?, '', 5.00, 1, ?)",
            [$business_name, $address, $phone, $password_hash, $logo_name]
        );

        if ($insert) {
            $restaurant_id = last_id();
            $start  = date('Y-m-d H:i:s');
            $expiry = date('Y-m-d H:i:s', strtotime('+1 month'));

            // Insert subscription
            query(
                "INSERT INTO subscriptions (restaurant_id, plan, start_date, expiry_date, status)
                 VALUES (?, '1 month', ?, ?, 'active')",
                [$restaurant_id, $start, $expiry]
            );

            header("Location: login.php?registered=1");
            exit;
        } else {
            $error = "❌ Registration failed!";
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Business Registration | Restaurant Billing</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
/* --- Reset --- */
* { margin:0; padding:0; box-sizing:border-box; font-family:'Poppins', sans-serif; }
body { background: linear-gradient(135deg, #4f46e5, #9333ea); height:100vh; display:flex; justify-content:center; align-items:center; }
.container { background:#fff; width:400px; padding:40px 30px; border-radius:15px; box-shadow:0 8px 25px rgba(0,0,0,0.2); text-align:center; animation: fadeIn 0.8s ease; }
.container h2 { color:#333; font-weight:600; margin-bottom:25px; font-size:26px; }
.container input[type="text"], .container input[type="password"], .container textarea { width:100%; padding:12px; margin:10px 0 20px 0; border:1px solid #ccc; border-radius:8px; font-size:15px; transition:all 0.3s ease; }
.container input:focus, .container textarea:focus { border-color:#4f46e5; outline:none; box-shadow:0 0 6px rgba(79,70,229,0.3); }
.container textarea { resize:vertical; min-height:80px; max-height:150px; }
.container button { width:100%; padding:12px; border:none; background:#4f46e5; color:white; font-weight:600; border-radius:8px; font-size:16px; cursor:pointer; transition:background 0.3s ease; }
.container button:hover { background:#3730a3; }
.container p[style] { background:#fee2e2; color:#b91c1c; padding:10px; border-radius:6px; margin-bottom:15px; font-size:14px; }
.container p { margin-top:20px; font-size:14px; }
.container a { color:#4f46e5; text-decoration:none; font-weight:500; }
.container a:hover { text-decoration:underline; }
@keyframes fadeIn { from { opacity:0; transform:translateY(-15px); } to { opacity:1; transform:translateY(0); } }
@media (max-width:450px) { .container { width:90%; padding:30px 20px; } }
</style>
</head>
<body>
<div class="container">
  <h2>Business Registration</h2>
  <?php if(isset($error)) echo "<p style='color:red;'>$error</p>"; ?>

  <form method="POST" enctype="multipart/form-data">
      <input type="text" name="business_name" placeholder="Business Name" required>
      <input type="text" name="phone" placeholder="Phone Number" required>
      <textarea name="address" placeholder="Business Address" required></textarea>

      <div style="text-align:left; width:100%;">
          <label style="font-weight:500; display:block; margin-bottom:5px;">Upload Logo</label>
          <input type="file" name="logo" accept="image/*" required
                 style="width:100%; padding:12px; border:1px solid #ccc; border-radius:8px; font-size:15px; margin-bottom:20px;">
      </div>

      <input type="password" name="password" placeholder="Password" required>
      <button type="submit">Register</button>
  </form>

  <p>Already registered? <a href="login.php">Login</a></p>
</div>
</body>
</html>
