import { useEffect, useState } from "react";

// const API_URL = "http://localhost:8000/"; // adjust if needed
const API_URL = "http://localhost/react-frontend/backend"; // adjust if needed

function App() {
  const [users, setUsers] = useState([]);
  const [form, setForm] = useState({ id: null, name: "", email: "" });

  const fetchUsers = () => {
    fetch(`${API_URL}/read.php`)
      .then((res) => res.json())
      .then((data) => setUsers(data));
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const saveUser = () => {
    const url = form.id ? `${API_URL}/update.php` : `${API_URL}/create.php`;
    fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    })
      .then((res) => res.json())
      .then(() => {
        setForm({ id: null, name: "", email: "" });
        fetchUsers();
      });
  };

  const editUser = (user) => {
    setForm(user);
  };

  const deleteUser = (id) => {
    fetch(`${API_URL}/delete.php`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id }),
    })
      .then((res) => res.json())
      .then(() => fetchUsers());
  };

  return (
    <div style={{ padding: "20px", fontFamily: "sans-serif" }}>
      <h2>React + PHP CRUD</h2>

      <div style={{ marginBottom: "10px" }}>
        <input
          type="text"
          placeholder="Name"
          value={form.name}
          onChange={(e) => setForm({ ...form, name: e.target.value })}
        />
        <input
          type="email"
          placeholder="Email"
          value={form.email}
          onChange={(e) => setForm({ ...form, email: e.target.value })}
        />
        <button onClick={saveUser}>
          {form.id ? "Update" : "Add"}
        </button>
      </div>

      <table border="1" cellPadding="8">
        <thead>
          <tr>
            <th>ID</th><th>Name</th><th>Email</th><th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {users.map((u) => (
            <tr key={u.id}>
              <td>{u.id}</td>
              <td>{u.name}</td>
              <td>{u.email}</td>
              <td>
                <button onClick={() => editUser(u)}>Edit</button>
                <button onClick={() => deleteUser(u.id)}>Delete</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default App;
